Search code examples
c#gzipgzipstream

Extracted file changes Date modified


When I tried to extract my file using winrar, It retains the date modified of the file inside a .gz. But when I extracted it using a code that is working (I got from other blogs):

 public static void Decompress(FileInfo fileToDecompress)
    {
        using (FileStream originalFileStream = fileToDecompress.OpenRead())
        {
            string currentFileName = fileToDecompress.FullName;
            string date = fileToDecompress.LastWriteTimeUtc.ToString();
            MessageBox.Show(date);
            string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

            using (FileStream decompressedFileStream = File.Create(newFileName))
            {
                using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                {
                    decompressionStream.CopyTo(decompressedFileStream);
                    Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
                }
            }
        }
    }

It changes the modified date of the extracted file to the current date which is the date and time I extracted it.

How can I able to retain the date modified of the file?

example the file in a .gz is dated as 8/13/2014 using a winrar it didn't change but when I use my code it changes to the current date I extracted it.


Solution

  • To be technically correct you are not extracting file but writing decompressed stream to another stream which is file in your case. After you look at it that way is obvious that last write date of file is changed.

    If you want to last write time of destination file to be the same as compressed filed, you can use File.SetLastWriteTime method (http://msdn.microsoft.com/en-US/library/system.io.file.setlastwritetime(v=vs.110).aspx):

    File.SetLastWriteTimeUtc(newFileName, fileToDecompress.LastWriteTimeUtc);