C# SharpZipLib:将单个文件压缩为单个压缩文件
我目前正在.NET2.0下使用SharpZipLib,通过它我需要将单个文件压缩到单个压缩归档文件。为此,我目前使用以下方法:C# SharpZipLib:将单个文件压缩为单个压缩文件,c#,compression,sharpziplib,C#,Compression,Sharpziplib,我目前正在.NET2.0下使用SharpZipLib,通过它我需要将单个文件压缩到单个压缩归档文件。为此,我目前使用以下方法: string tempFilePath = @"C:\Users\Username\AppData\Local\Temp\tmp9AE0.tmp.xml"; string archiveFilePath = @"C:\Archive\Archive_[UTC TIMESTAMP].zip"; FileInfo inFileInfo = new FileInfo(tem
string tempFilePath = @"C:\Users\Username\AppData\Local\Temp\tmp9AE0.tmp.xml";
string archiveFilePath = @"C:\Archive\Archive_[UTC TIMESTAMP].zip";
FileInfo inFileInfo = new FileInfo(tempFilePath);
ICSharpCode.SharpZipLib.Zip.FastZip fZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
fZip.CreateZip(archiveFilePath, inFileInfo.Directory.FullName, false, inFileInfo.Name);
这正是它应该工作的(ish),但是在测试时我遇到了一个小问题。假设我的临时目录(即包含未压缩输入文件的目录)包含以下文件:
tmp9AE0.tmp.xml //The input file I want to compress
xxx_tmp9AE0.tmp.xml // Some other file
yyy_tmp9AE0.tmp.xml // Some other file
wibble.dat // Some other file
当我运行压缩时,所有.xml
文件都包含在压缩存档中。这是因为传递给CreateZip
方法的最后一个fileFilter
参数。在引擎盖下,SharpZipLib正在执行模式匹配,这也会拾取前缀为xxx\uuz
和yyy\uz
的文件。我想它也会拾取任何已修复的内容
所以问题是,如何使用SharpZipLib压缩单个文件?然后,也许问题是如何格式化fileFilter
,以便匹配项只能拾取我要压缩的文件,而不拾取其他文件
顺便问一下,有没有任何理由说明为什么System.IO.Compression
不包括ZipStream
类?(它只支持GZipStream)
编辑:解决方案(来源于Hans Passant接受的答案)
这是我实现的压缩方法:
private static void CompressFile(string inputPath, string outputPath)
{
FileInfo outFileInfo = new FileInfo(outputPath);
FileInfo inFileInfo = new FileInfo(inputPath);
// Create the output directory if it does not exist
if (!Directory.Exists(outFileInfo.Directory.FullName))
{
Directory.CreateDirectory(outFileInfo.Directory.FullName);
}
// Compress
using (FileStream fsOut = File.Create(outputPath))
{
using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut))
{
zipStream.SetLevel(3);
ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(inFileInfo.Name);
newEntry.DateTime = DateTime.UtcNow;
zipStream.PutNextEntry(newEntry);
byte[] buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(inputPath))
{
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
zipStream.IsStreamOwner = true;
zipStream.Close();
}
}
}
这是一个XY问题,只是不要使用FastZip。遵循第一个示例以避免发生意外。至于你的旁白:ZipStream没有多大意义,因为ZIP是一种可以保存多个文件的归档格式。我想他们本可以为读写和ZIP提供一个完整的API,但这显然比GZipStream付出更多的努力。顺便说一句,由于您只压缩一个文件,有没有理由不想只使用GZip压缩,正如您所指出的,GZip压缩在框架内有支持?我很乐意,我可以用几行代码来实现这一点。它必须是压缩的,因为我们的“支持”部门无法处理gzip的复杂性(听起来有讽刺意味吗??)),但压缩的归档文件也包括所有目录。如果归档文件只包含根级别的文件,而不包含其他内容,则会更好。string entryName=System.IO.Path.GetFileName(filename);