2012-12-14 60 views
5

我使用的是最新版本的DotNetZip,並且我有一個帶有5個XML的zip文件。
我想打開zip文件,讀取XML文件,並使用XML的值設置String。
我該怎麼做?如何使用DotNetZip從zip中提取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 ? 
    } 
} 

由於

回答

14

ZipEntry具有Extract()過載,其提取到流。 (1)

這個答案How do you get a string from a 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); 
     } 
    } 
} 
+0

感謝卡森,爲我的作品。我正在使用Extract,但沒有與流,ty再次。 – Bruno

+1

我錯過了ms.Position = 0;非常感謝:) –

相關問題