从 .NET 可执行文件中提取构建日期
以编程方式确定 .NET 可执行文件的构建日期可能很棘手,因为许多开发人员只能访问构建号。 本文详细介绍了一种使用 C# 检索此信息的强大方法,利用 PE 标头的嵌入时间戳。
利用 PE 标头时间戳
PE(可移植可执行文件)标头存储反映可执行文件链接时间的时间戳。 Joe Spivey 的 C# 代码提供了一种便捷的访问方式:
<code class="language-csharp">public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null) { string filePath = assembly.Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; byte[] buffer = new byte[2048]; using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) stream.Read(buffer, 0, 2048); int offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset); int secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset); DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime linkTimeUtc = epoch.AddSeconds(secondsSince1970); TimeZoneInfo tz = target ?? TimeZoneInfo.Local; DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz); return localTime; }</code>
用法示例:
<code class="language-csharp">DateTime buildDate = Assembly.GetExecutingAssembly().GetLinkerTime();</code>
重要注意事项:虽然对 .NET Core 1.0 有效,但由于潜在的 PE 标头格式更改,此方法的准确性可能会在更高版本的 .NET Core 版本(1.1 及更高版本)中受到影响。
以上是如何以编程方式获取 .NET 可执行文件的构建日期?的详细内容。更多信息请关注PHP中文网其他相关文章!