Search code examples
c#visual-studiobuildbuild-process

update automatically constant value in code on each build in C# / Visual Studio


I would like to have a constant whose value would be updated automatically each time a project is built with the current date time. Is this possible?

For example, I would have a constant:

string LastBuildDate = "01/07/2014 19:20 PM"

Then, if I build 15 minutes later, this would automatically be updated to:

string LastBuildDate = "01/07/2014 19:35 PM"

It doesn't have to be specifically such a constant. I would like to be able to know when the application was last compiled and show it in the administration area of a website.


Solution

  • Apparently, the same functionality I was looking for can be done by setting the version in AssemblyInfo.cs to 1.0.*, as per below.

    [assembly: AssemblyVersion("1.0.*")]
    //[assembly: AssemblyFileVersion("1.0.0.0")]
    

    Then, I added the below code:

        public static DateTimeOffset GetLastApplicationBuildDateFromAssembly()
        {
    
            int gmtOfBuild = 1; //as the date/time is of the local machine where it was built, in my case +1 gmt
    
            var executingAssembly = Assembly.GetCallingAssembly();
            var executingAssemblyName = executingAssembly.GetName();
            var version = executingAssemblyName.Version;
            DateTimeOffset relativeDate = new DateTimeOffset(2000, 1, 1, 0, 0, 0, new TimeSpan(gmtOfBuild , 0, 0));
    
            int daysAfter1stJan2000 = version.Build;
            int secondsdAfterMidnight = version.MinorRevision * 2;
    
            var buildDate = relativeDate.AddDays(daysAfter1stJan2000).AddSeconds(secondsdAfterMidnight);
            return buildDate;
    
        }
    

    Reference: Can I automatically increment the file build version when using Visual Studio?