【问题标题】:Problems with creating ZIP file in c#在 C# 中创建 ZIP 文件的问题
【发布时间】:2012-06-11 09:03:40
【问题描述】:

我正在尝试通过此代码创建 zip 文件,但没有任何效果,ZipFile 的构造函数没有得到 () 只用参数重载,我没有SAVE 方法? 怎么了?

   using (ZipFile zip = new ZipFile())
        {
            zip.AddEntry("C://inetpub//wwwroot//Files//Wireframes//" + url, zip.Name);
            zip.AddDirectory("C://inetpub//wwwroot//Files//Wireframes//" + url);
            zip.Save(downloadFileName);
        }

【问题讨论】:

  • 您使用的是什么 zip 库?语法似乎来自 DotNetZip,但您的标签表示 SharpZipLib。
  • 提供更多关于你的代码中使用的DLL的信息。
  • 我正在使用ICSharpCode.SharpZipLib.Zip,ICSharpCode.SharpZipLib
  • 看看here。

标签: c# zip sharpziplib


【解决方案1】:

要使用 SharpZipLib 压缩整个目录,您可以尝试以下方法:

    private void ZipFolder(string folderName, string outputFile)
    { 
        string[] files = Directory.GetFiles(folderName);
        using (ZipOutputStream zos = new ZipOutputStream(File.Create(outputFile)))
        {
            zos.SetLevel(9); // 9 = highest compression
            byte[] buffer = new byte[4096];
            foreach (string file in files)
            {
                ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                entry.DateTime = DateTime.Now;
                zos.PutNextEntry(entry);
                using (FileStream fs = File.OpenRead(file))
                {
                   int byteRead;
                   do
                   {
                        byteRead = fs.Read(buffer, 0,buffer.Length);
                        zos.Write(buffer, 0, byteRead);
                   }
                   while (byteRead > 0);
                }
            }
            zos.Finish();
            zos.Close();
        }

如您所见,我们的代码与您的示例完全不同。
正如我在上面的评论中所说,您的示例似乎来自DotNetZip 如果您希望使用该库,您的代码将是:

using (ZipFile zip = new ZipFile())                    
{                        
    zip.AddFile("C://inetpub//wwwroot//Files//Wireframes//" + url);
    zip.AddDirectory("C://inetpub//wwwroot//Files//Wireframes//" + url, "WireFrames");
    zip.Save(downloadFileName);                    
}            

编辑:在某个目录中添加所有 PNG 文件

using (ZipFile zip = new ZipFile())                    
{                        
    string  filesPNG = Directory.GetFiles("C://inetpub//wwwroot//Files//Wireframes//" + url, "*.PNG);
    foreach(string file in filesPNG)
        zip.AddFile(file);
    zip.Save(downloadFileName);                    
}            

【讨论】:

  • private void ZipFolder() 不能 100% 工作,它只压缩 folderName 中的文件,没有子目录。
  • 是的,这是一个取自我自己的代码的示例,我不需要压缩子文件夹。
  • 在同一个站点中,有一个您需要的示例。 Look at this
  • 问题是我已经在该程序的其他内容中使用ICSharpCode.SharpZipLib.Zip,如果我删除它'第一个示例正在运行。但我需要这些命名空间来处理其他事情......使用SharpZipLib 的代码我无法工作......没有添加文件的选项
  • 不要使用C:盘根目录。尝试使用您具有读/写权限的子文件夹
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 2019-04-02
  • 1970-01-01
  • 2015-01-11
相关资源
最近更新 更多