Home > Backend Development > C++ > How Can I Programmatically Get the Build Date of a .NET Executable?

How Can I Programmatically Get the Build Date of a .NET Executable?

Mary-Kate Olsen
Release: 2025-01-22 01:07:09
Original
567 people have browsed it

How Can I Programmatically Get the Build Date of a .NET Executable?

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>
Copy after login

Example usage:

<code class="language-csharp">DateTime buildDate = Assembly.GetExecutingAssembly().GetLinkerTime();</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template