如何使用C#4.0从文件夹解压缩所有.Zip文件,而不使用任何OpenSource Dll?

SHE*_*ETE 21 c# unzip zipfile

我有一个包含.ZIP文件的文件夹.现在,我想使用C#将ZIP文件解压缩到特定文件夹,但不使用任何外部程序集或.Net Framework 4.5.

我搜索过,但没有找到任何使用Framework 4.0或更低版本解压缩*.zip文件的解决方案.

我尝试过GZipStream,但它只支持.gz而不支持.zip文件.

Den*_*nko 32

这是msdn的例子.System.IO.Compression.ZipFile是为了这个:

using System;
using System.IO;
using System.IO.Compression;

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";

            ZipFile.CreateFromDirectory(startPath, zipPath);

            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:对不起,我错过了你对.NET 4.0及以下版本的兴趣.必需的.NET framework 4.5及更高版本.

  • 我已经提到我有框架4.0而不是4.5很抱歉! (6认同)
  • @SHEKHAR SHETE,对不起.然而,答案可能对某人有帮助,所以我会离开它. (3认同)

TBD*_*TBD 14

我有同样的问题,发现了一篇非常简单的文章解决了这个问题. http://www.fluxbytes.com/csharp/unzipping-files-using-shell32-in-c/

你需要引用名为Microsoft Shell Controls And Automation(Interop.Shell32.dll)的COM库

代码(从文章中未触及,只是让你看到它是多么简单):

public static void UnZip(string zipFile, string folderPath)
{
    if (!File.Exists(zipFile))
        throw new FileNotFoundException();

    if (!Directory.Exists(folderPath))
        Directory.CreateDirectory(folderPath);

    Shell32.Shell objShell = new Shell32.Shell();
    Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
    Shell32.Folder sourceFile = objShell.NameSpace(zipFile);

    foreach (var file in sourceFile.Items())
    {
        destinationFolder.CopyHere(file, 4 | 16);
    }
}
Run Code Online (Sandbox Code Playgroud)

强烈建议阅读这篇文章 - 他为旗帜4 | 16带来了一个表达

编辑:几年后,我的应用程序,使用它,已经运行,我收到两个用户的投诉,突然之间应用程序停止工作.似乎CopyHere函数创建了临时文件/文件夹,但这些文件/文件夹从未被删除而导致出现问题.可以在System.IO.Path.GetTempPath()中找到这些文件的位置.

  • 我发现由于某种原因解压缩文件的时间与原始文件的时间不同,因为出于某种原因复制文件会重置秒数。例如:原始时间24/6/15 08:00:35复制的文件将是:24/6/15 08:00:00通常这没有什么区别,但是客户向我指出了:-/ (2认同)
  • @JeffS,当我在Win7上编译并且应用程序在XP上运行时,我遇到了同样的问题.我认为在一个版本的Windows上编译并在另一个版本上运行时会出现问题.请看这里:https://social.msdn.microsoft.com/Forums/vstudio/en-US/b25e2b8f-141a-4a1c-a73c-1cb92f953b2b/instantiate-shell32shell-object-in-windows-8?forum=clr (2认同)