C# でファイルとディレクトリを圧縮したい。インターネットでいくつかの解決策を見つけましたが、それらは非常に複雑で、プロジェクトで実行できませんでした。誰かが私に明確で効果的な解決策を提案できますか?
58804 次
10 に答える
25
名前空間GZipStream
で使用できますSystem.IO.Compression
.NET 2.0.
public static void CompressFile(string path)
{
FileStream sourceFile = File.OpenRead(path);
FileStream destinationFile = File.Create(path + ".gz");
byte[] buffer = new byte[sourceFile.Length];
sourceFile.Read(buffer, 0, buffer.Length);
using (GZipStream output = new GZipStream(destinationFile,
CompressionMode.Compress))
{
Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
destinationFile.Name, false);
output.Write(buffer, 0, buffer.Length);
}
// Close the files.
sourceFile.Close();
destinationFile.Close();
}
.NET 4
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and
// already compressed files.
if ((File.GetAttributes(fi.FullName)
& FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Extension != ".gz")
{
// Create the compressed file.
using (FileStream outFile =
File.Create(fi.FullName + ".gz"))
{
using (GZipStream Compress =
new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into
// the compression stream.
inFile.CopyTo(Compress);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
于 2012-06-22T09:29:03.450 に答える
2
System.IO.Packaging
と呼ばれる組み込みのクラスがありZipPackage
ます:
http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage(v=vs.100).aspx
于 2012-06-22T09:28:42.433 に答える
1
ms-dosコマンドラインプログラムcompact.exeを使用できます。cmdでパラメーターcompact.exeを確認し、.NETメソッドProcess.Start()を使用してこのプロセスを開始します。
于 2013-03-01T23:25:03.670 に答える
1
于 2012-06-22T09:27:43.903 に答える
0
.Net2.0以降と互換性のあるMSDNから取得したソースコード
public static void CompressFile(string path)
{
FileStream sourceFile = File.OpenRead(path);
FileStream destinationFile = File.Create(path + ".gz");
byte[] buffer = new byte[sourceFile.Length];
sourceFile.Read(buffer, 0, buffer.Length);
using (GZipStream output = new GZipStream(destinationFile,
CompressionMode.Compress))
{
Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
destinationFile.Name, false);
output.Write(buffer, 0, buffer.Length);
}
// Close the files.
sourceFile.Close();
destinationFile.Close();
}
于 2012-06-22T11:55:45.727 に答える
0
http://dotnetzip.codeplex.com/を使用してファイルまたはディレクトリをZIPします。.NETで直接実行するための組み込みクラスはありません。
于 2012-06-22T09:27:55.587 に答える