C#记录exe编译时间

场景:程序启动后需要获取exe的生成时间;

注意:不能使用exe的创建时间和最近修改时间,因为复制或者移动会造成更改;

方法:

1.在csproj中添加:

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
    <WriteLinesToFile File="Properties\BuildTime.cs" Lines="[assembly: System.Reflection.AssemblyMetadata(%22BuildTime%22, %22$([System.DateTime]::UtcNow.ToString(yyyy-MM-ddTHH:mm:ssZ))%22)]" Overwrite="true" />
  </Target>

2.重新生成后,将Properties下的BuildTime.cs包含在项目中;

 3.代码获取时间戳:

Assembly ass = Assembly.GetExecutingAssembly();
var attribute = ass.GetCustomAttribute<AssemblyMetadataAttribute>();
if (attribute != null && attribute.Key == "BuildTime")
    DateTime time = DateTime.Parse(attribute.Value);

  

 

posted @ 2025-05-08 18:03  [春风十里]  阅读(69)  评论(0)    收藏  举报