c# – 如何压缩文件

我想压缩C#中的文件和目录.我在互联网上找到了一些解决方案,但它们非常复杂,我无法在我的项目中运行它们.有人可以建议我一个清晰有效的解决方案吗?

解决方法

您可以在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());
                    }
                }
            }
        }
    }

http://msdn.microsoft.com/en-us/library/ms404280.aspx

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...