解决方法
您可以在System.IO.Compression命名空间中使用GZipStream
.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,buffer.Length); using (GZipStream output = new GZipStream(destinationFile,CompressionMode.Compress)) { Console.WriteLine("Compressing {0} to {1}.",sourceFile.Name,destinationFile.Name,false); output.Write(buffer,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()); } } } } }
原文地址:https://www.jb51.cc/csharp/93216.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。