如何压缩文件 [英] How to compress files

查看:192
本文介绍了如何压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想压缩一个文件和一个目录在C#。我在互联网上找到了一些解决方案,但他们是如此复杂,我无法在我的项目中运行它们。任何人都可以给我建议一个清晰有效的解决方案? c>

I want to compress a file and a directory in C#. I found some solution in Internet but they are so complex and I couldn't run them in my project. Can anybody suggest me a clear and effective solution?

推荐答案

System.IO.Compression 命名空间

You could use GZipStream in the System.IO.Compression namespace

.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());
                    }
                }
            }
        }
    }


$ b b

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

这篇关于如何压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆