This project is read-only.

How to append in a text file inside a zip

Mar 29, 2010 at 7:13 PM

I need File.Append sort of functionality inside a Zip files' entry

What i will do is just create a Zip file then for different function I

Have to appned the Text in and entry inside the Zip file.

I doesn't wanted to write all then create the text file and then save the entry in ZipFile.

My File can get from 10KB to 900MB of data.

Please suggest any thing



string strZipFileName = @"C:\";
            string strEntryName = strZipFileName + @"\Test.cpt";
            ZipFile zfValid = new ZipFile(@"C:\");            
            string[] strArr = { "dsf", "", "dsfsdf" };
            using (StreamWriter sw = File.AppendText(strEntryName))
                foreach (String str in strArr)//in actual i will get some info by an ienumerable<string function>

Mar 30, 2010 at 12:43 AM

I can't think of an easy way to append data to an existing entry in a zip file, without decompressing and re-compressing. Compression is done on the entire file, and so it isn't simple to just "append" additional compressed blocks.  You'd need to directly manipulate the DEFLATE format.  You are welcome to do that work yourself, but I don't think I want to do it.

The way I would do what you want:  in DotNetZip, it is possible to open an entry as a stream - this stream decompresses as you read it (see ZipEntry.OpenReader).  It is also possible to add an entry using a WriteDelegate.  DotNetZip calls this delegate upon Save().  Putting these things together, your WriteDelegate could call OpenReader, write all the data from the original entry, then append additional data.  This would decompress and re-compress of all the original data, but only in memory, without ever writing a temporary file to disk.  The code would look like this:

using (var zip1 = ZipFile.Read(zipFile))
    using (var zip = new ZipFile())
        zip.AddEntry(entryName, (name, stream) =>
                var src = zip1[name].OpenReader();
                int n;
                byte[] b = new byte[2048];
                while((n= src.Read(b,0,b.Length)) > 0)

                string update = String.Format("Updating zip file at {0}\n", DateTime.Now.ToString("G"));
                byte[] a = System.Text.Encoding.ASCII.GetBytes(update.ToCharArray());

File.Move(tempZipFile, zipFile);

You would need to save to a separate zip file, because you can't do the decompress/recompress thing I described without using 2 distinct zip files.  (or at the very least, 2 distinct zip entries).

If you have a 900mb file and you are doing small updates or small append operations, I would recommend not compressing the file until you are finished appending.

Good luck.


Mar 30, 2010 at 6:51 AM

Thnaks cheeso for nicely explaining it.

I will now first create all of my files in a temprorary folder then Add them in a zip file as i think that will be a better option.