c# - 压缩/解压缩文件夹和文件

标签 c# .net file compression

有谁知道在 C# 中快速压缩或解压缩文件和文件夹的好方法?可能需要处理大文件。

最佳答案

.Net 2.0 框架命名空间 System.IO.Compression 支持 GZip 和 Deflate 算法。这里有两种压缩和解压缩字节流的方法,您可以从文件对象中获取字节流。您可以在下面的方法中将 GZipStream 替换为 DefaultStream 以使用该算法。不过,这仍然存在处理使用不同算法压缩的文件的问题。

public static byte[] Compress(byte[] data)
{
    MemoryStream output = new MemoryStream();

    GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true);
    gzip.Write(data, 0, data.Length);
    gzip.Close();

    return output.ToArray();
}

public static byte[] Decompress(byte[] data)
{
    MemoryStream input = new MemoryStream();
    input.Write(data, 0, data.Length);
    input.Position = 0;

    GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);

    MemoryStream output = new MemoryStream();

    byte[] buff = new byte[64];
    int read = -1;

    read = gzip.Read(buff, 0, buff.Length);

    while (read > 0)
    {
        output.Write(buff, 0, read);
        read = gzip.Read(buff, 0, buff.Length);
    }

    gzip.Close();

    return output.ToArray();
}

关于c# - 压缩/解压缩文件夹和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/145/

相关文章:

.net - WF4 AssignActivity - 多行语句中断设计器

PHP从上传的文本文件中读取?

android - 从内部存储器读取图像android给出空指针异常

c# - 命名管道在写入时挂起

c# - 使用反射从字符串中获取属性值

c# - ZeroMQ (NetMQ) TCP 传输可以在同一进程中的发布者和订阅者之间使用吗?

c++ - 读取windows文件; _stat 返回不正确的值

c# - 检查 LINQ 查询是否返回行

c# 使用命名空间解析 xml

.net - 如何使用 MouseMove 事件在面板内移动标签?