首页 > 解决方案 > 将 ZIP 文件提取到内存(不是磁盘)

问题描述

我需要将 zip 文件提取到内存(而不是磁盘)。我无法将其保存到目录中,即使是暂时的。

有没有办法将 zip 文件提取到内存中,并在那里执行“文件”功能?

我无法将文件作为文件流打开,因为这不允许我读取元数据(上次写入时间、属性等)。一些但不是所有的文件属性可以从 zip 条目本身中读取,但这对于我的目的来说是不够的。

我一直在使用:

using (ZipArchive archive = ZipFile.OpenRead(openFileDialog.FileName))  // Read files from the zip file
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        if(entry.Name.EndsWith(".txt", StringComparison.InvariantCultureIgnoreCase)) // get .txt file
        {
            FileStream fs = entry.Open() as FileStream;
        }
    }
}

谢谢。

标签: c#.netzip

解决方案


下面的代码提供了一种将文件作为字符串数组放入内存的方法,但不清楚您要求的文件函数。其他评论者提到了 ExternalAttributes,它依赖于操作系统,因此获得有关问题空间的更多信息是相关的。

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

namespace StackOverflowSampleCode
{
    class Program
    {
        /// <summary>
        /// Validate the extension is correct
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="ext"></param>
        /// <returns></returns>
        static bool validateExtension(ZipArchiveEntry entry, string ext)
        {
            return entry.Name.EndsWith(
                        ext,
                        StringComparison.InvariantCultureIgnoreCase);
        }

        /// <summary>
        /// Convert the entry into an array of strings
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        static string[] extractFileStrings(ZipArchiveEntry entry)
        {
            string[] file;
            // Store into MemoryStream
            using (var ms = entry.Open() as MemoryStream)
            {
                // Verify we are at the start of the stream
                ms.Seek(0, SeekOrigin.Begin);

                // Handle the bytes of the memory stream
                // by converting to array of strings
                file = ms.ToString().Split(
                    Environment.NewLine, // OS agnostic
                    StringSplitOptions.RemoveEmptyEntries);
            }

            return file;
        }

        static void Main(string[] args)
        {
            string fileName = "";

            using (ZipArchive archive = ZipFile.OpenRead(fileName))
            {
                foreach (var entry in archive.Entries)
                {
                    // Limit results to files with ".txt" extension
                    if (validateExtension(entry, ".txt"))
                    {
                        var file = extractFileStrings(entry);

                        foreach (var line in file)
                        {
                            Console.WriteLine(line);
                        }

                        Console.WriteLine($"Last Write Time: {entry.LastWriteTime}");
                        Console.WriteLine($"External Attributes: {entry.ExternalAttributes}");
                    }
                }
            }
        }
    }
}

推荐阅读