How to Use DotNetZip to extract XML file from zip

2019-06-19 17:06发布

问题:

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

回答1:

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);
        }
    }
}