Display build date in a user-friendly way
When displaying the build details of your application, it is crucial to present it in a format that is easy for users to understand. Most users care less about the build number and more about knowing whether they have the latest version.
Query build number and date
While it is possible to get the build number directly using Assembly.GetExecutingAssembly().GetName().Version.ToString()
, getting the build date requires a different approach.
Retrieve linker timestamp
The most reliable way to determine the build date is to retrieve the linker timestamp in the executable's PE header. This timestamp represents the time the executable was built.
C# code to extract linker timestamp
Joe Spivey provided a C# code snippet for extracting the linker timestamp:
<code class="language-csharp">public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null) { var filePath = assembly.Location; const int c_PeHeaderOffset = 60; const int c_LinkerTimestampOffset = 8; var buffer = new byte[2048]; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) stream.Read(buffer, 0, 2048); var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset); var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset); var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var linkTimeUtc = epoch.AddSeconds(secondsSince1970); var tz = target ?? TimeZoneInfo.Local; var localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz); return localTime; }</code>
Examples of usage
To retrieve the build date in local time, use the following code:
<code class="language-csharp">var linkTimeLocal = Assembly.GetExecutingAssembly().GetLinkerTime();</code>
Instructions about .NET Core
While this method works in .NET Core 1.0, it is deprecated after .NET Core 1.1 and may produce incorrect results.
The above is the detailed content of How Can I Display a User-Friendly Build Date Instead of a Build Number in My Application?. For more information, please follow other related articles on the PHP Chinese website!