C# 读取文件编译生成的时间 (采用读取PE32时间)

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 }

 

posted @ 2022-05-06 22:07  _Ong  阅读(585)  评论(0编辑  收藏  举报