如何使用DotNetZip从zip文件中提取XML文件

6
我将使用最新版本的DotNetZip,并且我有一个包含5个XML文件的zip文件。
我想要打开这个zip文件,读取XML文件并用XML的值设置一个字符串。
我应该如何做呢?
代码:
//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 ?
    }
}

谢谢

1个回答

16

ZipEntry 有一个重载的 Extract() 方法可以将文件提取到流中。(1)

结合这个如何从MemoryStream获取字符串?的回答,您可以得到以下代码(未经测试):

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

谢谢Carson,这对我很有帮助。我之前使用了Extract但没有使用stream,再次感谢。 - Bruno

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接