In makefiles for C programs, it is common to see something like this:
echo char * gBuildSig ="%DATE% %TIME%"; > BuildTimestamp.c
And then the resulting C source file is compiled into the image. The above works on Windows because the %date% and %time% variables are known in cmd.exe, but a similar thing would work on Unix using cat.
You can do the same thing using C#. Once again, this is how it would look if you are using a makefile. You need a class, and a public static property.
BuildTimestamp.cs:
echo public static class Build { public static string Timestamp = "%DATE% %TIME%";} > BuildTimestamp.cs
And then for the thing you are building, a dependency and a delete:
MyApp.exe: BuildTimestamp.cs MyApp.cs
$(_CSC) /target:exe /debug+ /optimize- /r:System.dll /out:MyApp.exe MyApp.cs BuildTimestamp.cs
-del BuildTimestamp.cs
Be sure to delete the BuildTimestamp.cs file after you compile it; you don't want to re-use it. Then, in your app, just reference Build.Timestamp.
Using MSBuild or Visual Studio, it is more complicated. I couldn't get %date% or %time% to resolve. Those things are pseudo environment variables, I guess that is why. So I resorted to an indirect way to get a timestamp, using the Touch task with AlwaysCreate = true. That creates an empty file. The next step writes source code into the same file, referencing the timestamp of the file. One twist - I had to escape the semicolon.
Your pre-build step should build the target "BuildTimestamp". And be sure to include that file into the compile. And delete it afterwards, in the post-build step.
<ItemGroup>
<StampFile Include="BuildTimestamp.cs"/>
</ItemGroup>
<Target Name="BuildTimestamp"
Outputs="@(StampFile)">
<Message Text="Building timestamp..." />
<Touch
AlwaysCreate="true"
Files="@(StampFile)" />
<WriteLinesToFile
File="@(StampFile)"
Lines='public static class Build { public static string Timestamp = "%(StampFile.CreatedTime)" %3B }'
Overwrite="true" />
</Target>