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

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

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

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

这是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); } } } 

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

我有同样的问题,发现了一篇非常简单的文章解决了这个问题。 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); } } 

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

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

ZipPackage可能是一个开始的地方。 它位于System.IO.Packaging中 ,可在.NET 4.0中使用

并非接近上面提到的.NET 4.5方法的简单性,但看起来它可以做你想要的。

.NET 3.5有一个DeflateStream。 您必须为目录等信息创建结构,但PKWare已发布此信息。 我编写了一个解压缩实用程序,一旦为它创建了结构,它就不是特别繁琐了。

我遇到了同样的问题并通过C#代码通过cmd shell调用7-zip可执行文件解决了这个问题,如下所示,

 string zipped_path = "xxx.7z"; string unzipped_path = "yyy"; string arguments = "e " + zipped_path + " -o" + unzipped_path; System.Diagnostics.Process process = Launch_in_Shell("C:\\Program Files (x86)\\7-Zip\\","7z.exe", arguments); if (!(process.ExitCode == 0)) throw new Exception("Unable to decompress file: " + zipped_path); 

并将Launch_in_Shell(...)定义为,

 public static System.Diagnostics.Process Launch_in_Shell(string WorkingDirectory, string FileName, string Arguments) { System.Diagnostics.ProcessStartInfo processInfo = new System.Diagnostics.ProcessStartInfo(); processInfo.WorkingDirectory = WorkingDirectory; processInfo.FileName = FileName; processInfo.Arguments = Arguments; processInfo.UseShellExecute = true; System.Diagnostics.Process process = System.Diagnostics.Process.Start(processInfo); return process; } 

缺点:你需要在你的机器上安装7zip,我只尝试使用“.7z”文件。 希望这可以帮助。

在.net 4.0中,Deflate和GZip无法处理Zip文件,但您可以使用shell函数来解压缩文件。

 public FolderItems Extract() { var shell = new Shell(); var sf = shell.NameSpace(_zipFile.Path); return sf.Items(); } 

调用extract函数时,可以保存返回的folderItems

  FolderItems Fits = Extract(); foreach( var s in Fits) { shell.Namespace("TargetFolder").copyhere(s); }