且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-14 21:55:01

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.