2013-02-03 35 views
1

我使用文本框創建表單,客戶希望將此文本框中的所有更改存儲到zip存檔。是否可以直接在zip文件中更改文件內容?

我使用http://dotnetzip.codeplex.com 和我有例子的代碼:

using (ZipFile zip = new ZipFile()) 
    { 
    zip.AddFile("text.txt");  
    zip.Save("Backup.zip"); 
    } 

,我不希望創建的每個時間溫度的text.txt和zip回來。 我可以訪問text.txt作爲Stream裏面的zip文件並保存文本嗎?

+2

請注意:ZIP格式並不打算用作虛擬存儲,因此幾乎所有修改都會導致大部分歸檔文件被重寫。 –

+1

你絕對是對的@ EugeneMayevski'EldoSCorp如果這是真正的意圖,那麼一個zip文件並不是專門用於大量數據的可行解決方案。 – Steve

回答

1

DotNetZip中有一個使用Stream的方法,其方法爲AddEntry

String zipToCreate = "Content.zip"; 
String fileNameInArchive = "Content-From-Stream.bin"; 
using (System.IO.Stream streamToRead = MyStreamOpener()) 
{ 
    using (ZipFile zip = new ZipFile()) 
    { 
    ZipEntry entry= zip.AddEntry(fileNameInArchive, streamToRead); 
    zip.Save(zipToCreate); // the stream is read implicitly here 
    } 
} 

使用LinqPad一個小測試表明,它可以使用一個MemoryStream來構建zip文件

void Main() 
{ 
    UnicodeEncoding uniEncoding = new UnicodeEncoding(); 
    byte[] firstString = uniEncoding.GetBytes("This is the current contents of your TextBox"); 
    using(MemoryStream memStream = new MemoryStream(100)) 
    { 
     memStream.Write(firstString, 0 , firstString.Length); 
     // Reposition the stream at the beginning (otherwise an empty file will be created in the zip archive 
     memStream.Seek(0, SeekOrigin.Begin); 
     using (ZipFile zip = new ZipFile()) 
     { 
      ZipEntry entry= zip.AddEntry("TextBoxData.txt", memStream); 
      zip.Save(@"D:\temp\memzip.zip"); 
     } 
    } 
} 
0

我發現可以利用字符串作爲PARAM另一種方法:

zip.RemoveEntry(entry); 
    zip.AddEntry(entry.FileName, text, ASCIIEncoding.Unicode); 

如果條目已經存在,我們可以先刪除它。

相關問題