我正在使用ICSharpCode.SharpZipLib.Zip.FastZip
压缩文件,但我遇到了一个问题:
当我尝试压缩文件名中包含特殊字符的文件时,它不起作用。当文件名中没有特殊字符时,它可以工作。
我正在使用ICSharpCode.SharpZipLib.Zip.FastZip
压缩文件,但我遇到了一个问题:
当我尝试压缩文件名中包含特殊字符的文件时,它不起作用。当文件名中没有特殊字符时,它可以工作。
我认为您不能使用 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();
}
FastZip
如果你愿意,你可以继续使用,但你需要给它一个ZipEntryFactory
创建ZipEntry
s 的 s IsUnicodeText = true
。
var zfe = new ZipEntryFactory { IsUnicodeText = true };
var fz = new FastZip { EntryFactory = zfe };
fz.CreateZip("out.zip", "C:\in", true, null);
您必须下载并编译最新版本的 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);
}
}
}
}
尝试从文件名中取出特殊字符,即替换它。您的Filename.Replace("&", "&");
可能性 1:您将文件名传递给正则表达式文件过滤器。
可能性 2:zip 文件中不允许使用这些字符(或者至少 SharpZipLib 是这样认为的)