.NET5以上显示build time
date
Sep 27, 2022
slug
10062
status
Published
tags
C#
summary
type
Post
Add a class like this to your project:
namespace SuperDuper
{
[AttributeUsage(AttributeTargets.Assembly)]
public class BuildDateTimeAttribute : Attribute
{
public string Date { get; set; }
public BuildDateTimeAttribute(string date)
{
Date = date;
}
}
}
Update the
.csproj
of your project to include something like this:<ItemGroup>
<AssemblyAttribute Include="SuperDuper.BuildDateTime">
<_Parameter1>$([System.DateTime]::Now.ToString("s"))</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
Note that
_Parameter1
is a magical name - it means the first (and only) argument to the constructor of our BuildDateTime
attribute class.That's all that is needed to record the build datetime in your assembly.
And then to read the build datetime of your assembly, do something like this:
private static DateTime? getAssemblyBuildDateTime()
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var attr = Attribute.GetCustomAttribute(assembly, typeof(BuildDateTimeAttribute)) as BuildDateTimeAttribute;
if (DateTime.TryParse(attr?.Date, out DateTime dt))
return dt;
else
return null;
}
Note (per Flydog57 in the comments) that if your
.csproj
has property GenerateAssemblyInfo
listed in it and set to false, the build won't generate assembly info and you'll get no BuildDateTime info in your assembly. So either do not mention GenerateAssemblyInfo
in your .csproj
(this is the default behaviour for a new project, and GenerateAssemblyInfo
defaults to true if not specifically set to false), or explicitly set it to true.