本文整理汇总了C#中ZipFile.AddFile方法的典型用法代码示例。如果您正苦于以下问题:C# ZipFile.AddFile方法的具体用法?C# ZipFile.AddFile怎么用?C# ZipFile.AddFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ZipFile
的用法示例。
在下文中一共展示了ZipFile.AddFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: button1_Click
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
ZipFile zf = new ZipFile("C:\\Users\\cpaine\\Desktop\\MyZipFile.zip");
zf.AddDirectoryByName("Adam");
zf.AddFile(ofd.FileName, "Adam");
//zf.AddDirectory(fbd.SelectedPath, "");
if.Save;
}
}
示例2: Error_Save_NoFilename
public void Error_Save_NoFilename()
{
string testBin = TestUtilities.GetTestBinDir(CurrentDir);
string resourceDir = Path.Combine(testBin, "Resources");
Directory.SetCurrentDirectory(TopLevelDir);
string filename = Path.Combine(resourceDir, "TestStrings.txt");
Assert.IsTrue(File.Exists(filename), String.Format("The file '{0}' doesnot exist.", filename));
// add an entry to the zipfile, then try saving, never having specified a filename. This should fail.
using (ZipFile zip = new ZipFile())
{
zip.AddFile(filename, "");
zip.Save(); // FAIL: don't know where to save!
}
// should never reach this
Assert.IsTrue(false);
}
示例3: CreateSmallZip
private void CreateSmallZip(string zipFileToCreate)
{
string sourceDir = CurrentDir;
for (int i = 0; i < 3; i++)
sourceDir = Path.GetDirectoryName(sourceDir);
// the list of filenames to add to the zip
string[] fileNames =
{
Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"),
Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"),
Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"),
};
using (ZipFile zip = new ZipFile())
{
for (int j = 0; j < fileNames.Length; j++)
zip.AddFile(fileNames[j], "");
zip.Save(zipFileToCreate);
}
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate),
fileNames.Length,
"Wrong number of entries.");
}
示例4: Test5
static void Test5()
{
using (var zf = new ZipFile())
{
zf.AddFile("XCode.pdb");
zf.AddFile("NewLife.Core.pdb");
zf.Write("test.zip");
zf.Write("test.7z");
}
//using (var zf = new ZipFile("Test.lzma.zip"))
//{
// foreach (var item in zf.Entries.Values)
// {
// Console.WriteLine("{0} {1}", item.FileName, item.CompressionMethod);
// }
// zf.Extract("lzma");
//}
}
示例5: SaveEpubFile
/// <summary>
/// Save the EPUB using Ionic zip library
/// </summary>
/// <param name="EpubFileName"></param>
private void SaveEpubFile(String EpubFileName)
{
if (File.Exists(EpubFileName))
File.Delete(EpubFileName);
using (ZipFile zip = new ZipFile(EpubFileName))
{
// MUST save the 'mimetype' file as the first file and non-compressed
zip.ForceNoCompression = true;
zip.AddFile(Path.Combine(mainDir, "mimetype"), "");
// Can compress all other files
zip.ForceNoCompression = false;
zip.AddDirectory(metaDir, "META-INF");
zip.AddDirectory(opsDir, "OPS");
zip.Save();
Directory.Delete(mainDir, true);
if (ddlType.Text == "Html")
if (workingFileName.ToLower() != tbxFileName.Text.ToLower())
File.Delete(workingFileName);
}
}
示例6: Password_Extract_WrongPassword
public void Password_Extract_WrongPassword()
{
string ZipFileToCreate = Path.Combine(TopLevelDir, "MultipleEntriesDifferentPasswords.zip");
Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate);
string SourceDir = CurrentDir;
for (int i = 0; i < 3; i++)
SourceDir = Path.GetDirectoryName(SourceDir);
Directory.SetCurrentDirectory(TopLevelDir);
string[] filenames =
{
Path.Combine(SourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"),
Path.Combine(SourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"),
};
string[] passwords =
{
"12345678",
"0987654321",
};
int j = 0;
using (ZipFile zip = new ZipFile(ZipFileToCreate))
{
for (j = 0; j < filenames.Length; j++)
{
zip.Password = passwords[j];
zip.AddFile(filenames[j], "");
}
zip.Save();
}
// now try to extract
using (ZipFile zip = new ZipFile(ZipFileToCreate))
{
for (j = 0; j < filenames.Length; j++)
zip[Path.GetFileName(filenames[j])].ExtractWithPassword("unpack", ExtractExistingFileAction.OverwriteSilently, "WrongPassword");
}
}
示例7: Error_AddFile_Twice
public void Error_AddFile_Twice()
{
int i;
// select the name of the zip file
string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_Twice.zip");
// create the subdirectory
string subdir = Path.Combine(TopLevelDir, "files");
Directory.CreateDirectory(subdir);
// create a bunch of files
int numFilesToCreate = _rnd.Next(23) + 14;
for (i = 0; i < numFilesToCreate; i++)
TestUtilities.CreateUniqueFile("bin", subdir, _rnd.Next(10000) + 5000);
// Create the zip archive
Directory.SetCurrentDirectory(TopLevelDir);
using (ZipFile zip1 = new ZipFile(zipFileToCreate))
{
zip1.StatusMessageTextWriter = System.Console.Out;
string[] files = Directory.GetFiles(subdir);
zip1.AddFiles(files, "files");
zip1.Save();
}
// this should fail - adding the same file twice
using (ZipFile zip2 = new ZipFile(zipFileToCreate))
{
zip2.StatusMessageTextWriter = System.Console.Out;
string[] files = Directory.GetFiles(subdir);
for (i = 0; i < files.Length; i++)
zip2.AddFile(files[i], "files");
zip2.Save();
}
}
示例8: Error_ReadCorruptedZipFile
[ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several.
public void Error_ReadCorruptedZipFile()
{
int i;
string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile.zip");
string sourceDir = CurrentDir;
for (i = 0; i < 3; i++)
sourceDir = Path.GetDirectoryName(sourceDir);
Directory.SetCurrentDirectory(TopLevelDir);
// the list of filenames to add to the zip
string[] filenames =
{
Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"),
Path.Combine(sourceDir, "Tools\\Unzip\\bin\\Debug\\Unzip.exe"),
Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"),
Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"),
};
// create the zipfile, adding the files
using (ZipFile zip = new ZipFile())
{
for (i = 0; i < filenames.Length; i++)
zip.AddFile(filenames[i], "");
zip.Save(zipFileToCreate);
}
// now corrupt the zip archive
IntroduceCorruption(zipFileToCreate);
try
{
// read the corrupted zip - this should fail in some way
using (ZipFile zip = new ZipFile(zipFileToCreate))
{
foreach (var e in zip)
{
System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}",
e.FileName, e.CompressedSize, e.UsesEncryption);
e.Extract("extract");
}
}
}
catch (Exception exc1)
{
throw new ZipException("expected", exc1);
}
}
示例9: btnGenerateAdminStatsGadget_Click
protected void btnGenerateAdminStatsGadget_Click(object sender, EventArgs e)
{
if (!HasWriteAccess)
return;
string gadgetFile = Path.GetTempPath() + Config.Misc.GadgetsPrefix + " Admin Stats.gadget";
if (File.Exists(gadgetFile)) File.Delete(gadgetFile);
using (ZipFile zip = new ZipFile(gadgetFile))
{
zip.BaseDir = Config.Directories.Home + @"\Gadgets\AdminStats\gadget\";
string[] filenames = Directory.GetFiles(Config.Directories.Home + @"\Gadgets\AdminStats\gadget");
foreach (String filename in filenames)
{
ZipEntry.FileParserDelegate parser = null;
if (filename.Contains("gadget.htm"))
parser = new ZipEntry.FileParserDelegate(FileParser);
zip.AddFile(filename, false, parser);
}
zip.Save();
}
Response.Clear();
Response.AppendHeader("content-disposition",
String.Format("attachment; filename=\"{0}.gadget\"",
Config.Misc.GadgetsPrefix + " Admin Stats"));
Response.TransmitFile(gadgetFile);
Response.End();
}
示例10: DoCollect
/////////////////////////////////////////////////////
// //
// DoCollect() //
// //
/////////////////////////////////////////////////////
//Description: Collects all files identified in the scan
// as malicious and stuffs them into a
// password-protected, encrypted ZIP file.
//
// NOTE: depends on DoSignatureScan()
//
//
//Returns: true if successful
//////////////////////////////////////////////////////
private unsafe bool DoCollect()
{
AgentScanLog.AppendLine("");
AgentScanLog.AppendLine("*********************************************");
AgentScanLog.AppendLine(" COLLECT ");
AgentScanLog.AppendLine("*********************************************");
AgentScanLog.AppendLine("");
AgentScanLog.AppendLine("COLLECT: Collecting evidence files...");
//collect the following files to wrap up in archive file:
// 1. all identified malware files
// 2. infection log (Infection_Log.txt) which we create
// 3. usb device list file (USB_Devices.txt) which we create
// 4. .net installation log (if exists)
//
//---------------------------------
// BUILD ZIP NAME
//---------------------------------
ZipFileName = Collect.BuildZipName(TotalFindingsCount);
ZipFile zip = new ZipFile(ZipFileName);
if (AgentSettings.ContainsKey("Reporting_Archive_Password"))
{
IntPtr pptr = IntPtr.Zero;
//do this secure string thing if password specified
char[] str = AgentSettings["Reporting_Archive_Password"].ToCharArray();
fixed (char* pChars = str)
{
ZipPassword = new SecureString(pChars, str.Length);
}
//decrypt our password in memory
pptr = Marshal.SecureStringToBSTR(ZipPassword);
zip.Password = Marshal.PtrToStringBSTR(pptr);
//zero the password memory
Marshal.ZeroFreeBSTR(pptr);
}
zip.TempFileFolder = ".";
ArrayList CollectList = new ArrayList();
int count = 0;
AgentScanLog.AppendLine("COLLECT: Searching file signature matches for files...");
//loop through file signatures
foreach (CwXML.FileSignatureMatch fileMatch in AgentSignatureMatches.FileSignatureMatches)
if (Collect.AddToZip(zip, fileMatch.FullPath))
count++;
AgentScanLog.AppendLine("COLLECT: Added " + count + " files.");
count = 0;
AgentScanLog.AppendLine("COLLECT: Searching registry signature matches for files...");
//loop through registry signatures
foreach (CwXML.RegistrySignatureMatch registryMatch in AgentSignatureMatches.RegistrySignatureMatches)
if (registryMatch.IsFileOnDisk)
if (Collect.AddToZip(zip, registryMatch.RegistryValueData))
count++;
AgentScanLog.AppendLine("COLLECT: Added " + count + " files.");
AgentScanLog.AppendLine("COLLECT: Generating infection summary report...");
//---------------------------------
// ADD INFECTION LOG
//---------------------------------
//2. infection log (Infection_Log.txt) which we create
StreamWriter infectionlog = new StreamWriter("InfectionLog.txt");
StringBuilder InfectionSummaryReport = new StringBuilder();
//print infection summary for each signature type
RegistryHelper RegHelper = new RegistryHelper();
FileHelper FileHelper = new FileHelper();
MemoryHelper MemHelper = new MemoryHelper();
RegHelper.PrintRegistryFindings(AgentSignatureMatches.RegistrySignatureMatches, ref InfectionSummaryReport);
FileHelper.PrintFileFindings(AgentSignatureMatches.FileSignatureMatches, ref InfectionSummaryReport);
MemHelper.PrintMemoryFindings(AgentSignatureMatches.MemorySignatureMatches, ref InfectionSummaryReport);
infectionlog.WriteLine(InfectionSummaryReport.ToString());
infectionlog.Close();
zip.AddFile("InfectionLog.txt");
AgentScanLog.AppendLine("COLLECT: Enumerating USB Devices...");
//---------------------------------
//.........这里部分代码省略.........
示例11: GeneraOXT
public static void GeneraOXT(Regles regles, string dirFitxer, string nomFitxer, CanviaString canvis)
{
// genera .oxt
String path = dirFitxer + nomFitxer + ".oxt";
File.Delete(path);
using (ZipFile zip = new ZipFile(path))
{
zip.AddFile(dirFitxer + nomFitxer + ".dic", "dictionaries");
zip.AddFile(dirFitxer + nomFitxer + ".aff", "dictionaries");
zip.AddFile(dirFitxer + @"..\..\OXT\" + "LICENSES-en.txt","");
zip.AddFile(dirFitxer + @"..\..\OXT\" + "LLICENCIES-ca.txt", "");
zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + nomFitxer + "\dictionaries.xcu", canvis, "\r\n", Encoding.UTF8), "dictionaries.xcu", "");
zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + nomFitxer + "\description.xml", canvis, "\r\n", Encoding.UTF8), "description.xml", "");
//zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + "release-notes_en.txt", canvia), "release-notes_en.txt", "");
//zip.AddStringAsFile(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + "release-notes_ca.txt", canvia), "release-notes_ca.txt", "");
zip.AddFile(dirFitxer + @"..\..\OXT\META-INF\" + "manifest.xml", "META-INF/");
zip.AddFile(dirFitxer + @"..\..\OXT\" + "SC-logo.png","");
zip.Save();
}
// genera update.xml, release-notes_en.txt i release-notes_ca.txt
path = dirFitxer + nomFitxer + ".update.xml";
using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8)) {
sw.Write(AdaptaFitxer(dirFitxer + @"..\..\OXT\update.xml", canvis, "\r\n", Encoding.UTF8));
}
string[] llengues = { "ca", "en" };
foreach (string llengua in llengues)
{
path = dirFitxer + "release-notes_" + llengua + ".html";
using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
{
sw.Write(AdaptaFitxer(dirFitxer + @"..\..\OXT\" + "release-notes_" + llengua + ".html", canvis, "\r\n", Encoding.UTF8));
}
}
}
示例12: UploadFiles
private void UploadFiles(StringCollection files)
{
if (files.Count > 1 && (bool)Properties.Settings.Default["combinezip"])
{
string tempfile = Path.GetTempPath() + "\\qpaste.zip";
File.Delete(tempfile);
using (ZipFile zip = new ZipFile(tempfile))
{
foreach (string file in files)
{
FileAttributes attr = File.GetAttributes(file);
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
Debug.WriteLine(Path.GetFileName(file));
zip.AddDirectory(file, Path.GetFileName(file));
}
else
{
zip.AddFile(file, "");
}
}
zip.Save();
}
Token token = UploadHelper.getToken(tempfile);
ClipboardHelper.PasteWithName("Multiple files", token.link);
UploadHelper.Upload(tempfile, token);
File.Delete(tempfile);
}
else
{
foreach (string file in files)
{
Token token = null;
FileAttributes attr = File.GetAttributes(file);
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
token = UploadHelper.getToken(file);
ClipboardHelper.PasteWithName(Path.GetFileName(file), token.link);
string tempfile = Path.GetTempPath() + "\\" + Path.GetFileNameWithoutExtension(file) + ".zip";
File.Delete(tempfile);
using (ZipFile zip = new ZipFile(tempfile))
{
zip.AddDirectory(file, "");
zip.Save();
}
UploadHelper.Upload(tempfile, token);
File.Delete(tempfile);
}
else
{
token = UploadHelper.getToken(file);
ClipboardHelper.PasteWithName(Path.GetFileName(file), token.link);
UploadHelper.Upload(file, token);
}
}
}
}
示例13: Password_AddEntryWithPasswordToExistingZip
public void Password_AddEntryWithPasswordToExistingZip()
{
string zipFileToCreate = "AddEntryWithPasswordToExistingZip.zip";
string[] filenames =
{
Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"),
Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"),
};
string[] checksums =
{
TestUtilities.GetCheckSumString(filenames[0]),
TestUtilities.GetCheckSumString(filenames[1]),
};
int j = 0;
using (ZipFile zip = new ZipFile())
{
for (j = 0; j < filenames.Length; j++)
zip.AddFile(filenames[j], "");
zip.Save(zipFileToCreate);
}
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 2,
"wrong number of entries.");
string fileX = Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Unzip"), "unzip.exe");
string checksumX = TestUtilities.GetCheckSumString(fileX);
string password = TestUtilities.GenerateRandomPassword() + "!";
using (ZipFile zip = FileSystemZip.Read(zipFileToCreate))
{
zip.Password = password;
zip.AddFile(fileX, "");
zip.Save(zipFileToCreate);
}
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 3,
"wrong number of entries.");
string unpackDir = "unpack";
string newpath, chk, baseName;
using (ZipFile zip = FileSystemZip.Read(zipFileToCreate))
{
for (j = 0; j < filenames.Length; j++)
{
baseName = Path.GetFileName(filenames[j]);
zip[baseName].Extract(unpackDir, ExtractExistingFileAction.OverwriteSilently);
newpath = Path.Combine(unpackDir, filenames[j]);
chk = TestUtilities.GetCheckSumString(newpath);
Assert.AreEqual<string>(checksums[j], chk, "Checksums do not match.");
}
baseName = Path.GetFileName(fileX);
zip[baseName].ExtractWithPassword(unpackDir,
ExtractExistingFileAction.OverwriteSilently,
password);
newpath = Path.Combine(unpackDir, fileX);
chk = TestUtilities.GetCheckSumString(newpath);
Assert.AreEqual<string>(checksumX, chk, "Checksums do not match.");
}
}
示例14: Error_AddFile_SpecifyingDirectory
public void Error_AddFile_SpecifyingDirectory()
{
string zipFileToCreate = "AddFile_SpecifyingDirectory.zip";
string badfilename = "ThisIsADirectory.txt";
Directory.CreateDirectory(badfilename);
using (ZipFile zip = new ZipFile())
{
zip.AddFile(badfilename); // should fail
zip.Save(zipFileToCreate);
}
}
示例15: SaveZipToFile
public void SaveZipToFile(FileName toSave)
{
ZipFile zip = new ZipFile(toSave.FullName);
foreach (ZipListItem item in list)
{
switch (item.Type)
{
case ZipListItemType.FILE:
zip.AddFile(item.Item, item.PathInZip.Path);
break;
case ZipListItemType.FOLDER:
zip.AddDirectory(item.Item, item.PathInZip.Path);
break;
default:
break;
}
}
zip.Save();
}