簡體   English   中英

提取的文件更改修改日期

[英]Extracted file changes Date modified

當我嘗試使用winrar提取文件時,它會在.gz中保留文件的修改日期。 但是當我使用正在運行的代碼(我從其他博客獲得)中提取它時:

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

它將提取文件的修改日期更改為當前日期,即我提取它的日期和時間。

我怎樣才能保留文件的修改日期?

例如.gz中的文件日期為2014年8月13日,使用winrar它沒有改變,但是當我使用我的代碼時,它會更改為我提取它的當前日期。

為了在技術上正確,您不是解壓縮文件,而是將解壓縮的流寫入另一個流,這是您的案例中的文件。 看一下之后,很明顯文件的最后寫入日期已經改變了。

如果要將目標文件的上次寫入時間與壓縮File.SetLastWriteTime相同,則可以使用File.SetLastWriteTime方法( http://msdn.microsoft.com/en-US/library/system.io.file.setlastwritetime( v = vs.110).aspx ):

File.SetLastWriteTimeUtc(newFileName, fileToDecompress.LastWriteTimeUtc);

使用.gz文件的修改時間是不合標准的,因為該文件很可能是通過http下載的,甚至可能是內存中的流。

繼馬克·阿德勒的建議之后:

    using (Stream s = File.OpenRead("file.gz"))
    {
        uint timestamp = 0;

        for (int x = 0; x < 4; x++)
            s.ReadByte();

        for (int x = 0; x < 4; x++)
        {
            timestamp += (uint)s.ReadByte() << (8*x);
        }

        DateTime innerFileTime = new DateTime(1970, 1, 1).AddSeconds(timestamp)
            // Gzip times are stored in universal time, I actually needed two calls to get it almost right, and the time was still out by an hour
            .ToLocalTime().ToLocalTime();


        // Reset stream position before decompressing file
        s.Seek(0, SeekOrigin.Begin);
    }

修改時間和日期可以在gzip頭的第四到第七個字節中找到,因此,最低有效字節優先:

MTIME(修改時間)這給出了正在壓縮的原始文件的最新修改時間。 時間是Unix格式,即自1970年1月1日格林尼治標准時間00:00:00以來的秒數。(請注意,這可能會導致MS-DOS和其他使用本地時間而不是通用時間的系統出現問題。)如果壓縮數據不是來自文件,MTIME設置為壓縮開始的時間。 MTIME = 0表示沒有時間戳可用。

GZIP文件格式規范中所述

然后,您可以使用此處的其他答案來設置寫入文件的修改時間。

暫無
暫無

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

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