【问题标题】:Get zip file entries in .NET 2.0在 .NET 2.0 中获取 zip 文件条目
【发布时间】:2016-03-04 06:02:13
【问题描述】:

我需要获取 ZIP 文件中每个条目的条目数和原始文件大小。在 .NET 4.5 上,我们可以使用 C# 类 ZipArchive 和 ZipFile,如下所示,但这些类在 .NET 2.0 中不可用。那我有什么选择呢?

using (ZipArchive archive = ZipFile.OpenRead(fileName))
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        Console.WriteLine("[INFO] Zip entry {0} original file size: [{1}]", entry.name, entry.Length);
     }
}

提前致谢。

【问题讨论】:

  • 我认为你是自己的。在这个时代还有什么理由使用 .NET 2.0?
  • 我公司的一些服务器仍在使用.NET 2.0。对于我之前编写的程序,我必须针对 .NET 2.0 进行编译。我将不得不找出我正在开发的这个新程序是否托管在更高的 .NET 版本上。

标签: c# .net .net-2.0 c#-2.0


【解决方案1】:

使用 [ICsharpZipLib] (https://icsharpcode.github.io/SharpZipLib/)

using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

public void ExtractZipFile(string archiveFilenameIn, string password, string outFolder) {
    ZipFile zf = null;
    try {
        FileStream fs = File.OpenRead(archiveFilenameIn);
        zf = new ZipFile(fs);
        if (!String.IsNullOrEmpty(password)) {
            zf.Password = password;     // AES encrypted entries are handled automatically
        }
        foreach (ZipEntry zipEntry in zf) {
            if (!zipEntry.IsFile) {
                continue;           // Ignore directories
            }
            String entryFileName = zipEntry.Name;
            // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
            // Optionally match entrynames against a selection list here to skip as desired.
            // The unpacked length is available in the zipEntry.Size property.

            byte[] buffer = new byte[4096];     // 4K is optimum
            Stream zipStream = zf.GetInputStream(zipEntry);

            // Manipulate the output filename here as desired.
            String fullZipToPath = Path.Combine(outFolder, entryFileName);
            string directoryName = Path.GetDirectoryName(fullZipToPath);
            if (directoryName.Length > 0)
                Directory.CreateDirectory(directoryName);

            // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
            // of the file, but does not waste memory.
            // The "using" will close the stream even if an exception occurs.
            using (FileStream streamWriter = File.Create(fullZipToPath)) {
                StreamUtils.Copy(zipStream, streamWriter, buffer);
            }
        }
    } finally {
        if (zf != null) {
            zf.IsStreamOwner = true; // Makes close also shut the underlying stream
            zf.Close(); // Ensure we release resources
        }
    }
}

【讨论】:

  • 我想第三方库是一个DLL文件,我需要把它放在哪里?
  • 是的,您可以将它放在您的项目文件夹中,并将其作为参考添加到您的项目中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
相关资源
最近更新 更多