如何通过使用C#.NET 4.5将文件从ZIP存档读取到内存,而无需先将其提取到文件中?

如何通过使用C#.NET 4.5将文件从ZIP存档读取到内存,而无需先将其提取到文件中?

问题描述:

.NET Framework 4.5通过System.IO.Compression中的类添加了对ZIP文件的支持.

.NET Framework 4.5 added support for ZIP files via classes in System.IO.Compression.

比方说,我有.ZIP存档,其根目录中有sample.xml文件.我想直接从存档读取此文件到内存流,然后将其反序列化为自定义.NET对象.最好的方法是什么?

Let's say I have .ZIP archive that has sample.xml file in the root. I want to read this file directly from archive to memory stream and then deserialize it to a custom .NET object. What is the best way to do this?

XmlSerializer.Deserialize() 手册页.

Adapted from the ZipArchive and XmlSerializer.Deserialize() manual pages.

ZipArchiveEntry类具有Open()方法,该方法将流返回到文件.

The ZipArchiveEntry class has an Open() method, which returns a stream to the file.

string zipPath = @"c:\example\start.zip";

using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
    var sample = archive.GetEntry("sample.xml");
    if (sample != null)
    {
        using (var zipEntryStream = sample.Open())
        {               
            XmlSerializer serializer = new XmlSerializer(typeof(SampleClass));  

            SampleClass deserialized = 
                (SampleClass)serializer.Deserialize(zipEntryStream);
        }
    }
} 

请注意,正如MSDN上记录的那样,您需要添加对.NET程序集System.IO.Compression.FileSystem的引用才能使用ZipFile类.

Note that, as documented on MSDN, you need to add a reference to the .NET assembly System.IO.Compression.FileSystem in order to use the ZipFile class.