Show GIT commit SHA in .NET applications

Many applications display their commit ID alongside the version. VS Code is one such example:

VS Code About Dialog

Though I've only tried this on ASP.NET sites, this should be doable in most .NET applications.

To do this we create a pre-build event that'll execute a git command and save it in a text file. We then add that generated text file as a string resource. The resource can will now be accessible from C#.

  1. Right click on the web application and click on properties.
  2. Go to the build events tab and type the following in the Pre-build event command line:
    git rev-parse HEAD --short > "$(ProjectDir)\CurrentCommit.txt"
    The command can obviously be replaced by anything you see fit.
  3. Save and build the project. (Ctrl+Shift+S, Ctrl+Shift+B)
  4. A new file called CurrentCommit.txt should be created in the root of your project.
  5. Go ahead and exclude it from Source Control
  6. In the projects properties page, go to the Resources tab and Add Existing File CurrentCommit.txt as a resource.

The contents of the generated file can now be accessed as: