Extracting the Build Date from .NET Executables
Determining a .NET executable's build date programmatically can be tricky, as many developers only have access to the build number. This article details a robust method for retrieving this information using C#, leveraging the PE header's embedded timestamp.
Leveraging the PE Header Timestamp
The PE (Portable Executable) header stores a timestamp reflecting the executable's link time. Joe Spivey's C# code provides a convenient way to access this:
<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>
Example usage:
<code class="language-csharp">DateTime buildDate = Assembly.GetExecutingAssembly().GetLinkerTime();</code>
Important Consideration: While effective for .NET Core 1.0, this approach's accuracy might be compromised in later .NET Core versions (1.1 and beyond) due to potential PE header format changes.
The above is the detailed content of How Can I Programmatically Get the Build Date of a .NET Executable?. For more information, please follow other related articles on the PHP Chinese website!