現在、.NET 2.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(tempFilePath);
ICSharpCode.SharpZipLib.Zip.FastZip fZip = new ICSharpCode.SharpZipLib.Zip.FastZip();
fZip.CreateZip(archiveFilePath, inFileInfo.Directory.FullName, false, inFileInfo.Name);
これは本来の (らしい) 正確な動作をしますが、テスト中に小さな落とし穴に遭遇しました。私の一時ディレクトリ (つまり、圧縮されていない入力ファイルを含むディレクトリ) に次のファイルが含まれているとします。
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のみ対応)
編集:解決策(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();
}
}
}