Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

zip

archive

.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?

like image 521
matori82 Avatar asked Dec 11 '13 13:12

matori82


People also ask

How can I read a Zip file without unzipping it?

zip lists the contents of a ZIP archive to ensure your file is inside. Use the -p option to write the contents of named files to stdout (screen) without having to uncompress the entire archive.

How do I extract data from a zip file?

Do one of the following: To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.

Is it possible to see the contents of a ZIP file in the terminal without unzipping it Linux?

Lucky for you, the unzip command has the -l option that displays the contents of a zip file without extracting them. To view a ZIP file's contents, run the unzip command to list ( -l ) the zip file's ( newdir. zip ) contents without extracting them.


1 Answers

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.

like image 99
CodeCaster Avatar answered Oct 12 '22 13:10

CodeCaster