2011-11-23 83 views
1

我一直在用asp.net開發一個web應用程序,我對SharZipLib有一些諷刺的問題。我有一個叫做Template.odt的文件(來自Open Office),這個文件是一個壓縮文件(就像docx),我們在裏面還有一些其他文件(諸如XML,圖像等)。我需要打開這個文件,更改一個名爲content.xml和styles.xml的文件,並保存在另一個.odt文件中並提供給我的客戶端。但我不確定我們是否可以使用臨時文件,所以我正在考慮如何使用MemoryStream來做到這一點。帶MemoryStream的SharpZipLib

看我得到了什麼:

protected byte[ GetReport() { 
    Stream inputStream = File.OpenRead(Server.MapPath("~/Odt/Template.odt")); 
    var zipInputStream = new ZipInputStream(inputStream); 
    var outputStream = new MemoryStream(); 
    var zipOutputStream = new ZipOutputStream(outputStream); 
    ZipEntry entry = zipInputStream.GetNextEntry(); 
    while (entry != null) {  

     if (entry.Name == "content.xml") 
      // how change the content ? 
     else if (entry.Name == "styles.xml") 
      // how change the content ? 

     // how to add it or create folders in the output ? 
     zipOutputStream.Write(???); 

     entry = zipInputStream.GetNextEntry(); 
    } 
    zipOutputStream.Flush(); 
    return outputStream.ToArray(); 
} 

我不知道這是否是正確的,但我認爲這是在路上。

我試圖從ZipEntry實例中拿ExtraData,但我知道它是空的,這是正常的嗎?

有人可以幫助我嗎?

謝謝

回答

1

如何,您可以更新內存ZIP文件的一個例子可以在這裏找到: http://wiki.sharpdevelop.net/SharpZipLib_Updating.ashx#Updating_a_zip_file_in_memory_1

在你的情況,你可能要content.xml加載到XmlDocumentXDocument進行修改 - 但這取決於你想要改變的東西。

作爲一個標記:使用流時,確保你正在處理它們。最簡單的方法是包裝在using語句操作:上

using(var inputStream = File.OpenRead(Server.MapPath("~/Odt/Template.odt"))) 
    { 
     // ... 
    } 

的更多信息:http://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C