Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement git id or build to c# application

Tags:

git

c#

I want to implement build id to about dialog of application that uses git. I know unix command to get a build id from git, but I have no idea how to grab it during build.

like image 923
Petr Avatar asked Dec 12 '25 05:12

Petr


1 Answers

Probably easiest way to do it is to use pre-build events. Solution is to call git command, dump output to a text file, include that file as a resource and load resource in C# code.

Add prebuild.cmd to your project directory with the following content:

cd %1
git log -n 1 --format=format:"%%h" HEAD > %2

Go to your project properties, tab Build Events and enter following command as pre-build event command line:

"$(ProjectDir)prebuild.cmd" "$(ProjectDir)" "$(ProjectDir)revision.txt"

Create an empty revision.txt file in your project directory (or run a build once). Add it to your project and set Embedded Resource build action for it. It also makes sense to add this file to .gitignore because it is auto-generated.

In your C# project add a new utility class:

public static class GitRevisionProvider
{
    public static string GetHash()
    {
        using(var stream = Assembly.GetExecutingAssembly()
                                    .GetManifestResourceStream(
                                    "DEFAULT_NAMESPACE" + "." + "revision.txt"))
        using(var reader = new StreamReader(stream))
        {
            return reader.ReadLine();
        }
    }
}

Don't forget to replace DEFAULT_NAMESPACE with default namespace of your project (it is prepended to resource names and there is no generic way to get that, you'll have to hard-code it).

This solution assumes that path to git exists in %PATH% environment variable.

like image 191
max Avatar answered Dec 14 '25 18:12

max