Search code examples
c#.netzipdotnetzip

Is it possible to change file content directly in zip file?


I have form with text box and customer wants to store all changes from this textbox to zip archive.

I am using http://dotnetzip.codeplex.com and i have example of code:

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

And i dont want to create each time temp text.txt and zip it back. Can I access text.txt as Stream inside zip file and save text there?


Solution

  • There is an example in DotNetZip that use a Stream with the method 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
      }
    }
    

    A little test using LinqPad shows that it is possible to use a MemoryStream to build the zip file

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