ICSharpCode.SharpZipLib.Zip.FastZip不压缩文件名中包含特殊字符的文件

时间:2010-11-22 13:06:47

标签: c# .net sharpziplib

我使用ICSharpCode.SharpZipLib.Zip.FastZip来压缩文件,但我遇到了问题:

当我尝试压缩文件名中包含特殊字符的文件时,它不起作用。当文件名中没有特殊字符时,它可以工作。

5 个答案:

答案 0 :(得分:6)

我认为你不能使用FastZip。您需要迭代文件并自己添加条目,指定:

entry.IsUnicodeText = true;

告诉SharpZipLib该条目是unicode。

string[] filenames = Directory.GetFiles(sTargetFolderPath);

// Zip up the files - From SharpZipLib Demo Code
using (ZipOutputStream s = new
    ZipOutputStream(File.Create("MyZipFile.zip")))
{
    s.SetLevel(9); // 0-9, 9 being the highest compression

    byte[] buffer = new byte[4096];

    foreach (string file in filenames)
    {
         ZipEntry entry = new ZipEntry(Path.GetFileName(file));

         entry.DateTime = DateTime.Now;
         entry.IsUnicodeText = true;
         s.PutNextEntry(entry);

         using (FileStream fs = File.OpenRead(file))
         {
             int sourceBytes;
             do
             {
                 sourceBytes = fs.Read(buffer, 0, buffer.Length);

                 s.Write(buffer, 0, sourceBytes);

             } while (sourceBytes > 0);
         }
    }
    s.Finish();
    s.Close();
 }

答案 1 :(得分:3)

如果您愿意,可以继续使用FastZip,但是您需要为ZipEntryFactory提供ZipEntry IsUnicodeText = true

var zfe = new ZipEntryFactory { IsUnicodeText = true };
var fz = new FastZip { EntryFactory = zfe };
fz.CreateZip("out.zip", "C:\in", true, null);

答案 2 :(得分:1)

您必须下载并编译最新版本的SharpZipLib库,以便使用

entry.IsUnicodeText = true;

这是您的代码段(略有修改):

FileInfo file = new FileInfo("input.ext");
using(var sw = new FileStream("output.zip", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    using(var zipStream = new ZipOutputStream(sw))
    {
        var entry = new ZipEntry(file.Name);
        entry.IsUnicodeText = true;
        zipStream.PutNextEntry(entry);

        using (var reader = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
            {
                byte[] actual = new byte[bytesRead];
                Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead);
                zipStream.Write(actual, 0, actual.Length);
            }
        }
    }
}

答案 3 :(得分:0)

可能性1:您正在将文件名传递给正则表达式文件过滤器。

可能性2:zip文件中不允许使用这些字符(或至少SharpZipLib认为如此)

答案 4 :(得分:0)

尝试从文件名中取出特殊字符,i,e替换它。 你的Filename.Replace("&", "&");

相关问题