Saving same file to stream multiple times produces different results

May 26, 2010 at 12:32 PM


I am zipping a file using a stream then writing the stream to file. If I run the code repeatedly the output is different each time - just a few bytes here and there. If I do the same thing using files everything is OK. I need to produce the same results each time, and I need to use streams to plug in to existing code.

This is a small sample I have pulled out of the project to try to isolate and fix. I've updated from 1.8 to 1.9 and tried using the new output stream class with the same results. Any ideas?

        static void CompressUsingStreams(string infile, int idx) {

            MemoryStream outstream = new MemoryStream();
            string outfile = Path.Combine(Path.GetDirectoryName(infile),
                                          Path.GetFileNameWithoutExtension(infile) + "." + idx + ".ddd");
            byte[] filebytes = File.ReadAllBytes(infile);

            if (File.Exists(outfile)) { File.Delete(outfile); }

            using (ZipOutputStream stream = new ZipOutputStream(outstream)){
                stream.CompressionLevel = CompressionLevel.BestCompression;
                stream.Write(filebytes, 0, filebytes.Length);
            File.WriteAllBytes(outfile, outstream.ToArray());


I've tried with a number of files. I can replicate just using a simple text file with a handful of words in.



May 26, 2010 at 12:47 PM

It's probably the timestamp.  Usiing a stream as input for an entry, the library by default uses the current time, which obviously will be different for each run.  Using a filesystem file , the library uses the timestamp on the file. 

You can overrride the timestamp used for an entry in a zip file by setting Atime, Mtime, Ctime or calling ZipEntry.SetEntryTimes.


May 26, 2010 at 12:51 PM

Hi Cheeso

That fixed it! Thanks for the extremely fast response, and thanks for a great library.