我使用了许多现有的代码,尝试以多种方式压缩文件夹,但仍然遇到时间和文件夹大小的问题(大小仍然大致相同)。
这段代码来自库的源代码,仍未产生想要的结果。
static void Main(string[] args)
{
//copyDirectory(@"C:\x", @"D:\1");
ZipOutputStream zip = new ZipOutputStream(File.Create(@"d:\2.zip"));
zip.SetLevel(9);
string folder = @"D:\music";
ZipFolder(folder, folder, zip);
zip.Finish();
zip.Close();
}
public static void ZipFolder(string RootFolder, string CurrentFolder, ZipOutputStream zStream)
{
string[] SubFolders = Directory.GetDirectories(CurrentFolder);
foreach (string Folder in SubFolders)
ZipFolder(RootFolder, Folder, zStream);
string relativePath = CurrentFolder.Substring(RootFolder.Length) + "/";
if (relativePath.Length > 1)
{
ZipEntry dirEntry;
dirEntry = new ZipEntry(relativePath);
dirEntry.DateTime = DateTime.Now;
}
foreach (string file in Directory.GetFiles(CurrentFolder))
{
AddFileToZip(zStream, relativePath, file);
}
}
private static void AddFileToZip(ZipOutputStream zStream, string relativePath, string file)
{
byte[] buffer = new byte[4096];
string fileRelativePath = (relativePath.Length > 1 ? relativePath : string.Empty) + Path.GetFileName(file);
ZipEntry entry = new ZipEntry(fileRelativePath);
entry.DateTime = DateTime.Now;
zStream.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
zStream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}