簡體   English   中英

是否可以直接在 zip 文件中更改文件內容?

[英]Is it possible to change file content directly in zip file?

我有帶有文本框的表單,客戶希望將此文本框的所有更改存儲到 zip 存檔。

我正在使用http://dotnetzip.codeplex.com並且我有代碼示例:

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

而且我不想每次都創建 temp text.txt 並將其壓縮回來。 我可以在 zip 文件中以 Stream 的形式訪問 text.txt 並將文本保存在那里嗎?

DotNetZip 中有一個示例,它使用帶有AddEntry方法的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");  
        }
     }
}

還有另一個 DotNetZip 方法接受文件路徑作為參數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM