C# 编译,将构建时间写入程序集(需要新项目结构)

来源:
https://stackoverflow.com/questions/1600962/displaying-the-build-date#

自定义特性

namespace SuperDuper
{
[AttributeUsage(AttributeTargets.Assembly)]
public class BuildDateTimeAttribute : Attribute
{
public DateTime Built { get; }
public BuildDateTimeAttribute(string date)
{
this.Built = DateTime.Parse(date);
}
}
}

编辑.csproj文件

<ItemGroup>
<AssemblyAttribute Include="SuperDuper.BuildDateTime">
<_Parameter1>$([System.DateTime]::Now.ToString("s"))</_Parameter1>
</AssemblyAttribute>
</ItemGroup>

获取

private static DateTime? getAssemblyBuildDateTime()
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var attr = Attribute.GetCustomAttribute(assembly, typeof(BuildDateTimeAttribute)) as BuildDateTimeAttribute;
return attr?.Built;
}

上方可以添加自定义的特性,下面是一个简化的方式
编辑.csproj文件

<ItemGroup>
<AssemblyMetadata Include="BuildTime1" Value="$([System.DateTime]::UtcNow.ToString(yyyy.MM.dd hh:mm:ss))" />
<AssemblyMetadata Include="BuildTime2" Value="$([System.DateTime]::UtcNow.ToString(o))" />
</ItemGroup>

获取

static void Main(string[] args)
{
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var attr = Attribute.GetCustomAttributes(assembly, typeof(AssemblyMetadataAttribute)).FirstOrDefault();
Console.WriteLine(((AssemblyMetadataAttribute)attr)?.Value);
Console.Read( );
}
posted @   trykle  阅读(81)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示