c# - 在 .net 中以编程方式解压缩文件

标签 c# unzip

我正在尝试以编程方式解压缩压缩文件。

我已经尝试在 .NET 中使用 System.IO.Compression.GZipStream 类,但是当我的应用程序运行时(实际上是单元测试)我得到了这个异常:

System.IO.InvalidDataException: The magic number in GZip header is not correct. Make sure you are passing in a GZip stream..

我现在意识到 .zip 文件与 .gz 文件不同,GZip zip

但是,由于我可以通过手动双击压缩文件然后单击“提取所有文件”按钮来提取文件,所以我认为在代码中也应该有一种方法可以做到这一点。

因此,我尝试使用 Process.Start() 并将压缩文件的路径作为输入。这会导致我的应用程序打开一个窗口,显示压缩文件中的内容。这一切都很好,但该应用程序将安装在服务器上,周围没有人可以单击“提取所有文件”按钮。

那么,如何让我的应用提取压缩文件中的文件?

或者有其他方法吗?我更喜欢用代码来做,而不需要下载任何第三方库或应用程序;安全部门对此并不太在意...

最佳答案

有了 .NET 4.5,您现在可以使用 .NET 框架解压缩文件:

using System;
using System.IO;

namespace ConsoleApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      string startPath = @"c:\example\start";
      string zipPath = @"c:\example\result.zip";
      string extractPath = @"c:\example\extract";

      System.IO.Compression.ZipFile.CreateFromDirectory(startPath, zipPath);
      System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
    }
  }
}

以上代码直接取自微软的文档:http://msdn.microsoft.com/en-us/library/ms404280(v=vs.110).aspx

ZipFile 包含在程序集 System.IO.Compression.FileSystem 中。 (感谢 nateirvin ...请参阅下面的评论)。您需要添加对框架程序集的 DLL 引用 System.IO.Compression.FileSystem.dll

关于c# - 在 .net 中以编程方式解压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/836736/

相关文章:

c# - 正确实现 EventArgs Empty

C# - 如何使用反射调用参数数量可变的静态方法

c# - 用单引号转换多行逗号分隔的文本框值

mysql - 检测到被阻止的 DLL : MySQL because of No-Installation Download

c# - 由外键 ef 4.3 组成的代码优先组合键

c# - 从 url 读取数据返回空值

linux - Zip 文件未通过 crontab 提取

powershell - 需要用于仅包含 Style.CSS 的特定文件夹的 ZIP 提取的 Powershell 脚本?

bash - 在 kotlin 脚本 [.kts] 中解压缩文件

java.util.zip.ZipException : invalid entry compressed size (expected 449 but got 455 bytes)