How to read file from ZIP archive to memory without extracting it to file first, by using C# .NET 4.5?

北城余情 提交于 2019-12-10 03:46:54

问题


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

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?


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/20520238/how-to-read-file-from-zip-archive-to-memory-without-extracting-it-to-file-first

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!