如何通过使用C#.NET 4.5将文件从ZIP存档读取到内存,而无需先将其提取到文件中? [英] How to read file from ZIP archive to memory without extracting it to file first, by using C# .NET 4.5?

查看:109
本文介绍了如何通过使用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?

推荐答案

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.

这篇关于如何通过使用C#.NET 4.5将文件从ZIP存档读取到内存,而无需先将其提取到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆