本文整理汇总了C#中ZipFile.Save方法的典型用法代码示例。如果您正苦于以下问题:C# ZipFile.Save方法的具体用法?C# ZipFile.Save怎么用?C# ZipFile.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ZipFile
的用法示例。
在下文中一共展示了ZipFile.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent
public void EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent()
{
var data = new byte[] { 1, 2, 3, 4 };
using (var stream = new MemoryStream())
{
using (var zip = new ZipFile())
{
zip.AddEntry(STR_TestBin, data);
zip.Save(stream);
stream.Position = 0;
using (var fs = new FileStream(@"C:\Users\Ivan.z\Documents\test.bin.zip", FileMode.OpenOrCreate))
{
fs.Position = 0;
stream.WriteTo(fs);
}
}
stream.Position = 0;
using (var zip = ZipFile.Read(stream))
{
using (var ms = new MemoryStream())
{
zip[STR_TestBin].Extract(ms);
var actual = ms.ToArray();
CollectionAssert.AreEquivalent(data, actual);
}
}
}
}
示例2: Metro_EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent
public void Metro_EmptyZip_AddEntry_SaveAndReRead_ShouldHaveSameContent()
{
var data = new byte[] { 1, 2, 3, 4 };
using (var stream = new MemoryStream())
{
using (var zip = new ZipFile())
{
zip.AddEntry(STR_TestBin, data);
zip.Save(stream);
}
stream.Position = 0;
using(var zip = ZipFile.Read(stream))
{
using(var ms = new MemoryStream())
{
zip[STR_TestBin].Extract(ms);
var actual = ms.ToArray();
CollectionAssert.AreEquivalent(data, actual);
}
}
}
}
示例3: CreateZip_AddDirectory_BlankName
public void CreateZip_AddDirectory_BlankName()
{
string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddDirectory_BlankName.zip");
using (ZipFile zip = new ZipFile(zipFileToCreate))
{
zip.AddDirectoryByName("");
zip.Save();
}
}
示例4: SaveAndRead_DNF
public void SaveAndRead_DNF()
{
using (var ms = new MemoryStream())
{
using (var zipFile = new ZipFile())
{
zipFile.Save(ms);
}
ms.Position = 0;
using (var readFile = ZipFile.Read(ms)) { }
}
}
示例5: DownloadMonthActualFile
public ActionResult DownloadMonthActualFile()
{
var files = _retailService.FindActuals(0, 0, 0);
var rootfolder = FileService.CreateActualFolder(files);
var filepath = ConfigurationManager.AppSettings["FilePath"];
var absolutePath = Server.MapPath(filepath);
ZipFile zip;
using (zip = new ZipFile(string.Format("{0}{1}", absolutePath, "report.zip")))
{
zip.TempFileFolder = absolutePath;
zip.AddDirectory(rootfolder, "Report");
zip.Save();
}
var zipFileContent = System.IO.File.ReadAllBytes(string.Format("{0}{1}", absolutePath, "report.zip"));
FileService.DeleteFile(string.Format("{0}{1}", absolutePath, "report.zip"));
Directory.Delete(rootfolder, true);
return File(zipFileContent, "application/x-compressed", "report.zip");
}
示例6: MainSuccessScenario
public void MainSuccessScenario()
{
var content1 = "content1 " + Guid.NewGuid();
var content2 = "content2 " + Guid.NewGuid();
using (var write = new ZipFile())
{
write.AddFileFromString("file1.txt", "", content1);
write.AddFileFromString("file2.txt", @"Dir1\Dir2\", content2);
write.AddDirectoryByName("Dir2/Dir3");
write.Save("testarc.zip");
write.Dispose();
}
using(var read = new ZipFile("testarc.zip"))
{
Assert.AreEqual(1, read.Entries.Where(e => e.IsDirectory).Count());
Assert.AreEqual(2, read.Entries.Where(e => !e.IsDirectory).Count());
var ms1 = new MemoryStream();
var ms2 = new MemoryStream();
read.Extract(@"file1.txt", ms1);
read.Extract(@"Dir1\Dir2\file2.txt", ms2);
ms1.Seek(0, SeekOrigin.Begin);
ms2.Seek(0, SeekOrigin.Begin);
read.Dispose();
Assert.AreEqual(content1, new StreamReader(ms1).ReadToEnd());
Assert.AreEqual(content2, new StreamReader(ms2).ReadToEnd());
}
using (var write2 = new ZipFile("testarc.zip"))
{
write2.RemoveEntry(@"file1.txt");
write2.Save();
write2.Dispose();
}
using (var read2 = new ZipFile("testarc.zip"))
{
Assert.AreEqual(1, read2.Entries.Where(e => !e.IsDirectory).Count());
Assert.AreEqual(1, read2.Entries.Where(e => e.IsDirectory).Count());
}
}
示例7: PackageWpfThemeResources
private static void PackageWpfThemeResources(string solutionFolder, string version)
{
Console.WriteLine(string.Empty);
Console.WriteLine("Packaging theme resources ZIP file.");
var outputFolder = solutionFolder + @"\Build\" + version + @"\";
var zipFileName = outputFolder + @"\CODE.Framework.WPFThemeResources." + version + ".zip";
if (File.Exists(zipFileName)) File.Delete(zipFileName);
var zip = new ZipFile(zipFileName);
var folders = Directory.GetDirectories(solutionFolder, "CODE.Framework.Wpf.Theme.*");
foreach (var folder in folders)
{
var parts = folder.Split('.');
var themeName = parts[parts.Length - 1];
var files = Directory.GetFiles(folder, "*.xaml");
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
AddFileToZip(zip, fileInfo, themeName + @"\" + fileInfo.Name);
}
}
zip.Save();
}
示例8: Password_BasicAddAndExtract
public void Password_BasicAddAndExtract()
{
int i;
string[] Passwords = { null, "Password!", TestUtilities.GenerateRandomPassword(), "A" };
Ionic.Zlib.CompressionLevel[] compressionLevelOptions = {
Ionic.Zlib.CompressionLevel.None,
Ionic.Zlib.CompressionLevel.BestSpeed,
Ionic.Zlib.CompressionLevel.Default,
Ionic.Zlib.CompressionLevel.BestCompression,
};
for (int k = 0; k < compressionLevelOptions.Length; k++)
{
for (int j = 0; j < Passwords.Length; j++)
{
TestContext.WriteLine("\n\n===================\nTrial ({0}) pw({1})", j, Passwords[j]);
string ZipFileToCreate = Path.Combine(TopLevelDir, String.Format("Password_BasicAddAndExtract-{0}-{1}.zip", k, j));
Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate);
Directory.SetCurrentDirectory(TopLevelDir);
string DirToZip = String.Format("zipthis-{0}-{1}", k, j);
Directory.CreateDirectory(DirToZip);
TestContext.WriteLine("\n---------------------creating files and computing checksums...");
int NumFilesToCreate = _rnd.Next(10) + 10;
string[] filenames = new string[NumFilesToCreate];
var checksums = new Dictionary<string, string>();
for (i = 0; i < NumFilesToCreate; i++)
{
filenames[i] = Path.Combine(DirToZip, String.Format("file{0:D3}.txt", i));
int sz = _rnd.Next(22000) + 3000;
//int sz = 1000;
var repeatedLine = String.Format("Line to Repeat... {0} {1} {2} filename: {3}", i, k, j, filenames[i]);
TestUtilities.CreateAndFillFileText(filenames[i], repeatedLine, sz);
string key = Path.GetFileName(filenames[i]);
checksums.Add(key, TestUtilities.GetCheckSumString(filenames[i]));
TestContext.WriteLine(" chk[{0}]={1}", key, checksums[key]);
}
TestContext.WriteLine("\n---------------------adding files to the archive...");
var sw = new StringWriter();
using (ZipFile zip = new ZipFile(ZipFileToCreate, sw))
{
zip.CompressionLevel = compressionLevelOptions[k];
zip.Password = Passwords[j];
zip.AddDirectory(Path.GetFileName(DirToZip));
zip.Save();
}
TestContext.WriteLine(sw.ToString());
Assert.AreEqual<int>(TestUtilities.CountEntries(ZipFileToCreate), NumFilesToCreate,
"The Zip file has an unexpected number of entries.");
TestContext.WriteLine("\n---------------------verifying checksums...");
using (ZipFile zip = ZipFile.Read(ZipFileToCreate))
{
foreach (ZipEntry e in zip)
TestContext.WriteLine("found entry: {0}", e.FileName);
var extractDir = String.Format("extract-{0}-{1}", k, j);
TestContext.WriteLine(" Extract with pw({0})", Passwords[j]);
foreach (ZipEntry e in zip)
{
e.ExtractWithPassword(extractDir, ExtractExistingFileAction.OverwriteSilently, Passwords[j]);
if (!e.IsDirectory)
{
byte[] c2 = TestUtilities.ComputeChecksum(Path.Combine(extractDir, e.FileName));
Assert.AreEqual<string>(checksums[e.FileName],
TestUtilities.CheckSumToString(c2), "The checksum of the extracted file is incorrect.");
}
}
}
TestContext.WriteLine("\n");
}
}
}
示例9: 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");
}
}
示例10: Password_UnsetEncryptionAfterSetPassword_wi13909_ZF
public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZF()
{
// Verify that unsetting the Encryption property after
// setting a Password results in no encryption being used.
// This method tests ZipFile.
string unusedPassword = TestUtilities.GenerateRandomPassword();
int numTotalEntries = _rnd.Next(46)+653;
string zipFileToCreate = "UnsetEncryption.zip";
using (var zip = new ZipFile())
{
zip.Password = unusedPassword;
zip.Encryption = EncryptionAlgorithm.None;
for (int i=0; i < numTotalEntries; i++)
{
if (_rnd.Next(7)==0)
{
string entryName = String.Format("{0:D5}", i);
zip.AddDirectoryByName(entryName);
}
else
{
string entryName = String.Format("{0:D5}.txt", i);
if (_rnd.Next(12)==0)
{
var block = TestUtilities.GenerateRandomAsciiString() + " ";
string contentBuffer = String.Format("This is the content for entry {0}", i);
int n = _rnd.Next(6) + 2;
for (int j=0; j < n; j++)
contentBuffer += block;
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer);
zip.AddEntry(entryName, contentBuffer);
}
else
zip.AddEntry(entryName, Stream.Null);
}
}
zip.Save(zipFileToCreate);
}
BasicVerifyZip(zipFileToCreate);
}
示例11: CreateZip_AddEntry_String_BlankName
public void CreateZip_AddEntry_String_BlankName()
{
string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddEntry_String_BlankName.zip");
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("", "This is the content.");
zip.Save(zipFileToCreate);
}
}
示例12: Error_LockedFile_wi13903
public void Error_LockedFile_wi13903()
{
TestContext.WriteLine("==Error_LockedFile_wi13903()");
string fname = Path.GetRandomFileName();
TestContext.WriteLine("create file {0}", fname);
TestUtilities.CreateAndFillFileText(fname, _rnd.Next(10000) + 5000);
string zipFileToCreate = "wi13903.zip";
var zipErrorHandler = new EventHandler<ZipErrorEventArgs>( (sender, e) =>
{
TestContext.WriteLine("Error reading entry {0}", e.CurrentEntry);
TestContext.WriteLine(" (this was expected)");
e.CurrentEntry.ZipErrorAction = ZipErrorAction.Skip;
});
// lock the file
TestContext.WriteLine("lock file {0}", fname);
using (var s = System.IO.File.Open(fname,
FileMode.Open,
FileAccess.Read,
FileShare.None))
{
using (var rawOut = File.Create(zipFileToCreate))
{
using (var nonSeekableOut = new Ionic.Zip.Tests.NonSeekableOutputStream(rawOut))
{
TestContext.WriteLine("create zip file {0}", zipFileToCreate);
using (var zip = new ZipFile())
{
zip.ZipError += zipErrorHandler;
zip.AddFile(fname);
// should trigger a read error,
// which should be skipped. Result will be
// a zero-entry zip file.
zip.Save(nonSeekableOut);
}
}
}
}
TestContext.WriteLine("all done, A-OK");
}
示例13: Error_EmptySplitZip
public void Error_EmptySplitZip()
{
string zipFileToCreate = "zftc.zip";
using (var zip = new ZipFile())
{
zip.MaxOutputSegmentSize = 1024*1024;
zip.Save(zipFileToCreate);
}
string extractDir = "extract";
using (var zip = ZipFile.Read(zipFileToCreate))
{
zip.ExtractAll(extractDir);
Assert.IsTrue(zip.Entries.Count == 0);
}
}
示例14: _Internal_ExtractExisting
private void _Internal_ExtractExisting(int flavor)
{
string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Error-Extract-ExistingFileWithoutOverwrite-{0}.zip", flavor));
string testBin = TestUtilities.GetTestBinDir(CurrentDir);
string resourceDir = Path.Combine(testBin, "Resources");
Assert.IsTrue(Directory.Exists(resourceDir));
Directory.SetCurrentDirectory(TopLevelDir);
var filenames = Directory.GetFiles(resourceDir);
using (ZipFile zip = new ZipFile(zipFileToCreate))
{
zip.AddFiles(filenames, "");
zip.Comment = "This is a Comment On the Archive";
zip.Save();
}
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filenames.Length,
"The zip file created has the wrong number of entries.");
// Extract twice: the first time should succeed.
// The second, should fail, because of a failed file overwrite.
// Unless flavor==3, in which case we overwrite silently.
for (int k = 0; k < 2; k++)
{
using (ZipFile zip = ZipFile.Read(zipFileToCreate))
{
if (flavor > 10)
zip.ExtractProgress += OverwriteDecider;
for (int j = 0; j < filenames.Length; j++)
{
ZipEntry e = zip[Path.GetFileName(filenames[j])];
if (flavor == 4)
e.Extract("unpack");
else
e.Extract("unpack", (ExtractExistingFileAction) flavor);
}
}
}
}
示例15: CreateSmallZip
private void CreateSmallZip(string zipFileToCreate)
{
// the list of filenames to add to the zip
string[] fileNames =
{
Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"),
Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.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.");
}