C# 讀取檔案編譯生成的時間 (採用讀取PE32時間)
阿新 • • 發佈:2022-05-07
C# 讀取檔案編譯生成的時間
(採用讀取PE32時間)
1 /// <summary> 2 /// 讀取檔案編譯生成的時間 (採用讀取PE32時間) 3 /// </summary> 4 /// <param name="fileName">檔案路徑</param> 5 /// <returns></returns> 6 public static DateTime GetPE32Time(string fileName) 7 { 8 int seconds=0; 9 DateTime dt = new DateTime(1970, 1, 1);//非法的PE32檔案 返回這個時間,PE32檔案編譯的基準時間 10 using (var br = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read))) 11 { 12 var bs = br.ReadBytes(2); 13 if (bs.Length != 2) return dt; 14 if (bs[0] != 'M' || bs[1] != 'Z') return dt; 15 br.BaseStream.Seek(0x3c, SeekOrigin.Begin);//File address of new exe header 16 var offset = br.ReadByte(); 17 br.BaseStream.Seek(offset, SeekOrigin.Begin); 18 bs = br.ReadBytes(4); 19 if (bs.Length != 4) return dt; 20 if (bs[0] != 'P' || bs[1] != 'E' || bs[2] != 0 || bs[3] != 0) return dt;21 bs = br.ReadBytes(2);//`6486`: Amd64 `4C01`:I386 22 bs = br.ReadBytes(2);//Number of sections 23 bs = br.ReadBytes(4);//Unix時間戳,秒 24 if (bs.Length != 4) return dt; 25 seconds = br.ReadInt32();//小端儲存的時間戳: `4D 43 71 62` -> 0x6271434D -> 2022/05/03 14:59:25 26 } 27 if(seconds>0) 28 return DateTime.SpecifyKind(dt, DateTimeKind.Utc).AddSeconds(seconds).ToLocalTime(); 29 else return dt; 30 }