Displaying the build date

前端 未结 25 2053
感动是毒
感动是毒 2020-11-22 11:36

I currently have an app displaying the build number in its title window. That\'s well and good except it means nothing to most of the users, who want to know if they have t

相关标签:
25条回答
  • 2020-11-22 12:21

    Jeff Atwood had a few things to say about this issue in Determining Build Date the hard way.

    The most reliable method turns out to be retrieving the linker timestamp from the PE header embedded in the executable file -- some C# code (by Joe Spivey) for that from the comments to Jeff's article:

    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;
    }
    

    Usage example:

    var linkTimeLocal = Assembly.GetExecutingAssembly().GetLinkerTime();
    

    UPDATE: The method was working for .Net Core 1.0, but stopped working after .Net Core 1.1 release(gives random years in 1900-2020 range)

    0 讨论(0)
  • 2020-11-22 12:23

    A small update on the "New Way" answer from Jhon.

    You need to build the path instead of using the CodeBase string when working with ASP.NET/MVC

        var codeBase = assembly.GetName().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
    
    0 讨论(0)
  • 2020-11-22 12:24

    The above method can be tweaked for assemblies already loaded within the process by using the file's image in memory (as opposed to re-reading it from storage):

    using System;
    using System.Runtime.InteropServices;
    using Assembly = System.Reflection.Assembly;
    
    static class Utils
    {
        public static DateTime GetLinkerDateTime(this Assembly assembly, TimeZoneInfo tzi = null)
        {
            // Constants related to the Windows PE file format.
            const int PE_HEADER_OFFSET = 60;
            const int LINKER_TIMESTAMP_OFFSET = 8;
    
            // Discover the base memory address where our assembly is loaded
            var entryModule = assembly.ManifestModule;
            var hMod = Marshal.GetHINSTANCE(entryModule);
            if (hMod == IntPtr.Zero - 1) throw new Exception("Failed to get HINSTANCE.");
    
            // Read the linker timestamp
            var offset = Marshal.ReadInt32(hMod, PE_HEADER_OFFSET);
            var secondsSince1970 = Marshal.ReadInt32(hMod, offset + LINKER_TIMESTAMP_OFFSET);
    
            // Convert the timestamp to a DateTime
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
            var dt = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tzi ?? TimeZoneInfo.Local);
            return dt;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 12:25

    For anyone that needs to get the compile time in Windows 8 / Windows Phone 8:

        public static async Task<DateTimeOffset?> RetrieveLinkerTimestamp(Assembly assembly)
        {
            var pkg = Windows.ApplicationModel.Package.Current;
            if (null == pkg)
            {
                return null;
            }
    
            var assemblyFile = await pkg.InstalledLocation.GetFileAsync(assembly.ManifestModule.Name);
            if (null == assemblyFile)
            {
                return null;
            }
    
            using (var stream = await assemblyFile.OpenSequentialReadAsync())
            {
                using (var reader = new DataReader(stream))
                {
                    const int PeHeaderOffset = 60;
                    const int LinkerTimestampOffset = 8;
    
                    //read first 2048 bytes from the assembly file.
                    byte[] b = new byte[2048];
                    await reader.LoadAsync((uint)b.Length);
                    reader.ReadBytes(b);
                    reader.DetachStream();
    
                    //get the pe header offset
                    int i = System.BitConverter.ToInt32(b, PeHeaderOffset);
    
                    //read the linker timestamp from the PE header
                    int secondsSince1970 = System.BitConverter.ToInt32(b, i + LinkerTimestampOffset);
    
                    var dt = new DateTimeOffset(1970, 1, 1, 0, 0, 0, DateTimeOffset.Now.Offset) + DateTimeOffset.Now.Offset;
                    return dt.AddSeconds(secondsSince1970);
                }
            }
        }
    

    For anyone that needs to get the compile time in Windows Phone 7:

        public static async Task<DateTimeOffset?> RetrieveLinkerTimestampAsync(Assembly assembly)
        {
            const int PeHeaderOffset = 60;
            const int LinkerTimestampOffset = 8;            
            byte[] b = new byte[2048];
    
            try
            {
                var rs = Application.GetResourceStream(new Uri(assembly.ManifestModule.Name, UriKind.Relative));
                using (var s = rs.Stream)
                {
                    var asyncResult = s.BeginRead(b, 0, b.Length, null, null);
                    int bytesRead = await Task.Factory.FromAsync<int>(asyncResult, s.EndRead);
                }
            }
            catch (System.IO.IOException)
            {
                return null;
            }
    
            int i = System.BitConverter.ToInt32(b, PeHeaderOffset);
            int secondsSince1970 = System.BitConverter.ToInt32(b, i + LinkerTimestampOffset);
            var dt = new DateTimeOffset(1970, 1, 1, 0, 0, 0, DateTimeOffset.Now.Offset) + DateTimeOffset.Now.Offset;
            dt = dt.AddSeconds(secondsSince1970);
            return dt;
        }
    

    NOTE: In all cases you're running in a sandbox, so you'll only be able to get the compile time of assemblies that you deploy with your app. (i.e. this won't work on anything in the GAC).

    0 讨论(0)
  • 2020-11-22 12:26

    You could launch an extra step in the build process that writes a date stamp to a file which can then be displayed.

    On the projects properties tab look at the build events tab. There is an option to execute a pre or post build command.

    0 讨论(0)
  • 2020-11-22 12:27

    I just do:

    File.GetCreationTime(GetType().Assembly.Location)
    
    0 讨论(0)
提交回复
热议问题