如何使用 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?
问题描述
.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?
推荐答案
改编自 ZipArchive
和 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.
这篇关于如何使用 C# .NET 4.5 将文件从 ZIP 存档读取到内存而不先将其解压缩到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!