如何在c#中列出.zip文件夹的内容?

如何在C#中列出压缩文件夹的内容? 例如,如何知道压缩文件夹中包含多少项,以及它们的名称是什么?

DotNetZip – .NET语言中的Zip文件操作

DotNetZip是一个易于使用的小型类库,用于处理.zip文件。 它可以使用VB.NET,C#(任何.NET语言)编写的.NET应用程序轻松创建,读取和更新zip文件。

用于读取zip的示例代码:

using (var zip = ZipFile.Read(PathToZipFolder)) { int totalEntries = zip.Entries.Count; foreach (ZipEntry e in zip.Entries) { e.FileName ... e.CompressedSize ... e.LastModified... } } 

.NET 4.5或更新版本最终具有使用System.IO.Compression.ZipArchive类处理通用zip文件的内置function( http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive程序集System.IO.Compression中的%28v = vs.110%29.aspx )。 不需要任何第三方库。

 string zipPath = @"c:\example\start.zip"; using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (ZipArchiveEntry entry in archive.Entries) { Console.WriteLine(entry.FullName); } } 

如果您使用的是.Net Framework 3.0或更高版本,请查看System.IO.Packaging命名空间 。 这将删除您对外部库的依赖性。

具体来看看ZipPackage类 。

检查SharpZipLib

 ZipInputStream inStream = new ZipInputStream(File.OpenRead(fileName)); while (inStream.GetNextEntry()) { ZipEntry entry = inStream.GetNextEntry(); //write out your entry's filename } 

Ick – 使用J#运行时的代码很可怕! 而且我不同意这是最好的方式 – 现在J#已经失去了支持。 如果你想要的只是ZIP支持,它是一个巨大的运行时。

怎么样 – 它使用DotNetZip (免费,MS-Public许可证)

 using (ZipFile zip = ZipFile.Read(zipfile) ) { bool header = true; foreach (ZipEntry e in zip) { if (header) { System.Console.WriteLine("Zipfile: {0}", zip.Name); if ((zip.Comment != null) && (zip.Comment != "")) System.Console.WriteLine("Comment: {0}", zip.Comment); System.Console.WriteLine("\n{1,-22} {2,9} {3,5} {4,9} {5,3} {6,8} {0}", "Filename", "Modified", "Size", "Ratio", "Packed", "pw?", "CRC"); System.Console.WriteLine(new System.String('-', 80)); header = false; } System.Console.WriteLine("{1,-22} {2,9} {3,5:F0}% {4,9} {5,3} {6:X8} {0}", e.FileName, e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), e.UncompressedSize, e.CompressionRatio, e.CompressedSize, (e.UsesEncryption) ? "Y" : "N", e.Crc32); if ((e.Comment != null) && (e.Comment != "")) System.Console.WriteLine(" Comment: {0}", e.Comment); } } 

我在这里比较新,所以也许我不明白发生了什么。 :-)这个post目前有4个答案,其中两个最佳答案已经被拒绝。 (Pearcewg和cxfx)pearcewg指出的文章非常重要,因为它澄清了SharpZipLib的一些许可问题。 我们最近评估了几个.Net压缩库,发现DotNetZip是目前最好的替代品。

非常简短的摘要:

  • System.IO.Packaging明显慢于DotNetZip。

  • SharpZipLib是GPL – 参见文章。

所以对于初学者,我投了两个答案。

金。

如果你像我一样并且不想使用外部组件,这里是我昨晚使用.NET的ZipPackage类开发的一些代码。

 var zipFilePath = "c:\\myfile.zip"; var tempFolderPath = "c:\\unzipped"; using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read)) { foreach (PackagePart part in package.GetParts()) { var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/'))); var targetDir = target.Remove(target.LastIndexOf('\\')); if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir); using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read)) { source.CopyTo(File.OpenWrite(target)); } } } 

注意事项:

  • ZIP存档必须在其根目录中有一个[Content_Types] .xml文件。 这对我的要求来说不是问题,因为我将控制通过此代码提取的任何ZIP文件的压缩。 有关[Content_Types] .xml文件的更多信息,请参阅: 打包数据的新标准本文的图13下面有一个示例文件。

  • 此代码使用.NET 4.0中的Stream.CopyTo方法

最好的方法是使用.NET内置的J#zipfunction,如MSDN所示: http : //msdn.microsoft.com/en-us/magazine/cc164129.aspx 。 在此链接中,有一个完整的应用程序读取和写入zip文件的工作示例。 对于列出zip文件内容的具体示例(在本例中为Silverlight .xap应用程序包),代码可能如下所示:

 ZipFile package = new ZipFile(packagePath); java.util.Enumeration entries = package.entries(); //We have to use Java enumerators because we //use java.util.zip for reading the .zip files while ( entries.hasMoreElements() ) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { string name = entry.getName(); Console.WriteLine("File: " + name + ", size: " + entry.getSize() + ", compressed size: " + entry.getCompressedSize()); } else { // Handle directories... } } 

艾德曼有一个正确的指针,但有问题 。 具体来说,您可能会发现打开zip文件的问题,但如果您打算创建pacakges,这是一个有效的解决方案。 ZipPackage实现了抽象的Package类,并允许操作zip文件。 有一个如何在MSDN中执行此操作的示例: http : //msdn.microsoft.com/en-us/library/ms771414.aspx 。 大致代码看起来像这样:

  string packageRelationshipType = @"http://schemas.microsoft.com/opc/2006/sample/document"; string resourceRelationshipType = @"http://schemas.microsoft.com/opc/2006/sample/required-resource"; // Open the Package. // ('using' statement insures that 'package' is // closed and disposed when it goes out of scope.) foreach (string packagePath in downloadedFiles) { Logger.Warning("Analyzing " + packagePath); using (Package package = Package.Open(packagePath, FileMode.Open, FileAccess.Read)) { Logger.OutPut("package opened"); PackagePart documentPart = null; PackagePart resourcePart = null; // Get the Package Relationships and look for // the Document part based on the RelationshipType Uri uriDocumentTarget = null; foreach (PackageRelationship relationship in package.GetRelationshipsByType(packageRelationshipType)) { // Resolve the Relationship Target Uri // so the Document Part can be retrieved. uriDocumentTarget = PackUriHelper.ResolvePartUri( new Uri("/", UriKind.Relative), relationship.TargetUri); // Open the Document Part, write the contents to a file. documentPart = package.GetPart(uriDocumentTarget); //ExtractPart(documentPart, targetDirectory); string stringPart = documentPart.Uri.ToString().TrimStart('/'); Logger.OutPut(" Got: " + stringPart); } // Get the Document part's Relationships, // and look for required resources. Uri uriResourceTarget = null; foreach (PackageRelationship relationship in documentPart.GetRelationshipsByType( resourceRelationshipType)) { // Resolve the Relationship Target Uri // so the Resource Part can be retrieved. uriResourceTarget = PackUriHelper.ResolvePartUri( documentPart.Uri, relationship.TargetUri); // Open the Resource Part and write the contents to a file. resourcePart = package.GetPart(uriResourceTarget); //ExtractPart(resourcePart, targetDirectory); string stringPart = resourcePart.Uri.ToString().TrimStart('/'); Logger.OutPut(" Got: " + stringPart); } } } 

最好的方法似乎是使用J#,如MSDN所示: http : //msdn.microsoft.com/en-us/magazine/cc164129.aspx

有更多c#.zip库指向不同的许可证,如本文中的SharpNetZip和DotNetZip: 如何从c#中的未压缩zip读取文件? 。 由于许可证要求,它们可能不合适。