我目前正在.NET 2.0下使用SharpZipLib,通過這個我需要將單個文件壓縮到單個壓縮存檔。爲了做到這一點,我現在使用的是以下幾點:SharpZipLib:將單個文件壓縮到單個壓縮文件
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
文件都包含在壓縮歸檔。原因是因爲最終的fileFilter
參數傳遞給了CreateZip
方法。 SharpZipLib正在執行模式匹配,並且這個文件還會以xxx_
和yyy_
作爲前綴。我認爲它也會提取任何後綴。
所以問題是,我如何使用SharpZipLib壓縮單個文件?然後,也許問題是我如何格式fileFilter
,以便比賽只能挑選我想壓縮的文件,而沒有其他的東西。
順便說一句,有沒有什麼理由爲什麼System.IO.Compression
不包括ZipStream
類? (它僅支持GZipStream)
編輯:溶液(從接受的答案衍生自漢斯帕桑特)
這是壓縮方法我實現:
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();
}
}
}
至於你說的話:ZipStream沒有多大意義,因爲ZIP是一種可以容納多個文件的存檔格式。我想他們可能已經提供了一個完整的API讀寫和ZIP,但是這顯然比GZipStream更加努力。 – 2011-01-26 13:29:38
作爲我自己的一部分,由於您只是壓縮一個文件,您是否有一個原因,您不希望只使用GZip壓縮,如您所注意的那樣,它在框架內提供了支持? – 2011-01-26 13:42:06