Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use DotNetZip to extract XML file from zip

I'm using the latest version of DotNetZip, and I have a zip file with 5 XMLs on it.
I want to open the zip, read the XML files and set a String with the value of the XML.
How can I do this?

Code:

//thats my old way of doing it.But I needed the path, now I want to read from the memory
string xfile = System.IO.File.ReadAllText(strNewFilePath, System.Text.Encoding.Default);

using (ZipFile zip = ZipFile.Read(this.uplZip.PostedFile.InputStream))
{
    foreach (ZipEntry theEntry in zip)
    {
        //What should I use here, Extract ?
    }
}

Thanks

like image 509
Bruno Avatar asked Dec 14 '12 23:12

Bruno


1 Answers

ZipEntry has an Extract() overload which extracts to a stream. (1)

Mixing in this answer to How do you get a string from a MemoryStream?, you'd get something like this (completely untested):

string xfile = System.IO.File.ReadAllText(strNewFilePath, System.Text.Encoding.Default);
List<string> xmlContents;

using (ZipFile zip = ZipFile.Read(this.uplZip.PostedFile.InputStream))
{
    foreach (ZipEntry theEntry in zip)
    {
        using (var ms = new MemoryStream())
        {
            theEntry.Extract(ms);

            // The StreamReader will read from the current 
            // position of the MemoryStream which is currently 
            // set at the end of the string we just wrote to it. 
            // We need to set the position to 0 in order to read 
            // from the beginning.
            ms.Position = 0;
            var sr = new StreamReader(ms);
            var myStr = sr.ReadToEnd();
            xmlContents.Add(myStr);
        }
    }
}
like image 97
Carson63000 Avatar answered Oct 28 '22 16:10

Carson63000