本文整理汇总了C#中ZipFile.AddDirectory方法的典型用法代码示例。如果您正苦于以下问题:C# ZipFile.AddDirectory方法的具体用法?C# ZipFile.AddDirectory怎么用?C# ZipFile.AddDirectory使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ZipFile
的用法示例。
在下文中一共展示了ZipFile.AddDirectory方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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");
}
示例2: 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");
}
}
}
示例3: Error_AddDirectory_SpecifyingFile
public void Error_AddDirectory_SpecifyingFile()
{
string zipFileToCreate = "AddDirectory_SpecifyingFile.zip";
string filename = "ThisIsAFile";
File.Copy(zipit, filename);
string baddirname = Path.Combine(TopLevelDir, filename);
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(baddirname); // FAIL
zip.Save(zipFileToCreate);
}
}
示例4: Error_Read_WithoutSave
public void Error_Read_WithoutSave()
{
string testBin = TestUtilities.GetTestBinDir(CurrentDir);
string resourceDir = Path.Combine(testBin, "Resources");
Directory.SetCurrentDirectory(TopLevelDir);
// add a directory to the zipfile, then try
// extracting, without a Save. This should fail.
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(resourceDir, "");
Assert.IsTrue(zip.Entries.Count > 0);
using (var s = zip[0].OpenReader()) // FAIL: has not been saved
{
byte[] buffer= new byte[1024];
int n;
while ((n= s.Read(buffer,0,buffer.Length)) > 0) ;
}
}
// should never reach this
Assert.IsTrue(false);
}
示例5: Error_Extract_WithoutSave
public void Error_Extract_WithoutSave()
{
string testBin = TestUtilities.GetTestBinDir(CurrentDir);
string resourceDir = Path.Combine(testBin, "Resources");
Directory.SetCurrentDirectory(TopLevelDir);
// add a directory to the zipfile, then try
// extracting, without a Save. This should fail.
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(resourceDir, "");
Assert.IsTrue(zip.Entries.Count > 0);
zip[0].Extract(); // FAIL: has not been saved
}
// should never reach this
Assert.IsTrue(false);
}
示例6: Spanned_Create
public void Spanned_Create()
{
string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
_txrx = TestUtilities.StartProgressMonitor("segmentedzip",
"Segmented Zips",
"Creating files");
_txrx.Send("pb 0 max 2");
int numFiles = _rnd.Next(10) + 8;
int overflows = 0;
string msg;
_txrx.Send("pb 1 max " + numFiles);
var update = new Action<int,int,Int64>( (x,y,z) => {
switch (x)
{
case 0:
_txrx.Send(String.Format("pb 2 max {0}", ((int)z)));
break;
case 1:
msg = String.Format("pb 2 value {0}", ((int)z));
_txrx.Send(msg);
break;
case 2:
_txrx.Send("pb 1 step");
_txrx.Send("pb 2 value 0");
msg = String.Format("status created {0}/{1} files",
y+1,
((int)z));
_txrx.Send(msg);
break;
}
});
_txrx.Send("status creating " + numFiles + " files...");
string[] filesToZip;
Dictionary<string, byte[]> checksums;
CreateLargeFilesWithChecksums(dirToZip, numFiles, update,
out filesToZip, out checksums);
_txrx.Send("pb 0 step");
int[] segmentSizes = { 0, 64*1024, 128*1024, 512*1024, 1024*1024,
2*1024*1024, 8*1024*1024, 16*1024*1024,
1024*1024*1024 };
_txrx.Send("status zipping...");
_txrx.Send(String.Format("pb 1 max {0}", segmentSizes.Length));
System.EventHandler<Ionic.Zip.SaveProgressEventArgs> sp = (sender1, e1) =>
{
switch (e1.EventType)
{
case ZipProgressEventType.Saving_Started:
_txrx.Send(String.Format("pb 2 max {0}", filesToZip.Length));
_txrx.Send("pb 2 value 0");
break;
case ZipProgressEventType.Saving_AfterWriteEntry:
TestContext.WriteLine("Saved entry {0}, {1} bytes",
e1.CurrentEntry.FileName,
e1.CurrentEntry.UncompressedSize);
_txrx.Send("pb 2 step");
break;
}
};
for (int m=0; m < segmentSizes.Length; m++)
{
string trialDir = String.Format("trial{0}", m);
Directory.CreateDirectory(trialDir);
string zipFileToCreate = Path.Combine(trialDir,
String.Format("Archive-{0}.zip",m));
int maxSegSize = segmentSizes[m];
msg = String.Format("status trial {0}/{1} (max seg size {2}k)",
m+1, segmentSizes.Length, maxSegSize/1024);
_txrx.Send(msg);
TestContext.WriteLine("=======");
TestContext.WriteLine("Trial {0}", m);
if (maxSegSize > 0)
TestContext.WriteLine("Creating a segmented zip...segsize({0})", maxSegSize);
else
TestContext.WriteLine("Creating a regular zip...");
var sw = new StringWriter();
bool aok = false;
try
{
using (var zip = new ZipFile())
{
zip.StatusMessageTextWriter = sw;
zip.BufferSize = 0x8000;
zip.CodecBufferSize = 0x8000;
zip.AddDirectory(dirToZip, "files");
zip.MaxOutputSegmentSize = maxSegSize;
zip.SaveProgress += sp;
//.........这里部分代码省略.........
示例7: 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();
}
示例8: Spanned_UpdateItem
public void Spanned_UpdateItem()
{
int numFilesToCreate = _rnd.Next(10) + 8;
int newFileCount = numFilesToCreate + _rnd.Next(3) + 3;
int[] segmentSizes = { 0,
64*1024, 128*1024, 512*1024, 1024*1024,
2*1024*1024, 8*1024*1024, 16*1024*1024,
1024*1024*1024 };
// create the first subdirectory (A)
string subdirA = Path.Combine(TopLevelDir, "A");
Directory.CreateDirectory(subdirA);
for (int j = 0; j < numFilesToCreate; j++)
{
var filename = Path.Combine(subdirA, String.Format("file{0:D3}.txt", j));
string repeatedLine = String.Format("Content for Original file {0}",
Path.GetFileName(filename));
TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000);
}
// create another subdirectory (B)
string subdirB = Path.Combine(TopLevelDir, "B");
Directory.CreateDirectory(subdirB);
for (int j = 0; j < newFileCount; j++)
{
var filename = Path.Combine(subdirB, String.Format("file{0:D3}.txt", j));
string repeatedLine = String.Format("Content for the updated file {0} {1}",
Path.GetFileName(filename),
System.DateTime.Now.ToString("yyyy-MM-dd"));
TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(1000) + 2000);
}
for (int m = 0; m < segmentSizes.Length; m++)
{
string trialDir = String.Format("trial-{0}", m);
string extractDir = String.Format("extract-{0}", m);
Directory.CreateDirectory(trialDir);
string zipFileToCreate = Path.Combine(trialDir, String.Format("Archive-{0}.zip", m));
int maxSegSize = segmentSizes[m];
int numSegs = 0;
TestContext.WriteLine("=======");
TestContext.WriteLine("Trial {0}", m);
if (maxSegSize > 0)
TestContext.WriteLine("Creating a segmented zip...segsize({0})", maxSegSize);
else
TestContext.WriteLine("Creating a regular zip...");
// Create the zip file
using (ZipFile zip1 = new ZipFile())
{
zip1.AddDirectory(subdirA, "");
zip1.MaxOutputSegmentSize = maxSegSize;
zip1.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive will be updated.";
zip1.Save(zipFileToCreate);
numSegs = zip1.NumberOfSegmentsForMostRecentSave;
}
// Verify the files are in the multiple segments
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), numFilesToCreate,
"The Zip file has the wrong number of entries before update.");
var files = Directory.GetFiles(trialDir);
var totalFileSize = files.Sum(f => new FileInfo(f).Length);
var expectedSegments = (maxSegSize == 0 ? 0 : totalFileSize / maxSegSize) + 1;
Assert.AreEqual(expectedSegments, numSegs);
Assert.AreEqual(expectedSegments, Directory.GetFiles(trialDir).Length);
// Update those files in the zip file
using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate))
{
zip2.UpdateDirectory(subdirB, "");
zip2.MaxOutputSegmentSize = maxSegSize;
zip2.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive has been updated.";
zip2.Save(zipFileToCreate);
numSegs = zip2.NumberOfSegmentsForMostRecentSave;
}
// Verify the number of files in the multiple segments
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), newFileCount,
"The Zip file has the wrong number of entries after update.");
files = Directory.GetFiles(trialDir);
totalFileSize = files.Sum(f => new FileInfo(f).Length);
expectedSegments = (maxSegSize == 0 ? 0 : totalFileSize / maxSegSize) + 1;
Assert.AreEqual(expectedSegments, numSegs);
Assert.AreEqual(expectedSegments, Directory.GetFiles(trialDir).Length);
// now extract the files and verify their contents
using (ZipFile zip3 = FileSystemZip.Read(zipFileToCreate))
{
foreach (string s in zip3.EntryFileNames)
{
string repeatedLine = String.Format("Content for the updated file {0} {1}",
s,
System.DateTime.Now.ToString("yyyy-MM-dd"));
zip3[s].Extract(extractDir);
//.........这里部分代码省略.........
示例9: 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);
}
}
}
}
示例10: 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);
}
}