Đây có thể là một thập kỷ quá muộn để hữu ích, nhưng có thể nó sẽ giúp người khác.
Bạn có thể thêm mục tiêu này đến file csproj của bạn, chỉ cần dán nó vào ở cuối:
<Target Name="BuildDate" BeforeTargets="CoreCompile">
<PropertyGroup>
<SharedAssemblyInfoFile>$(IntermediateOutputPath)CustomAssemblyInfo.cs</SharedAssemblyInfoFile>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(SharedAssemblyInfoFile)" />
</ItemGroup>
<ItemGroup>
<AssemblyAttributes Include="AssemblyMetadata">
<_Parameter1>AssemblyDate</_Parameter1>
<_Parameter2>$([System.DateTime]::UtcNow.ToString("u"))</_Parameter2>
</AssemblyAttributes>
</ItemGroup>
<WriteCodeFragment Language="C#" OutputFile="$(SharedAssemblyInfoFile)" AssemblyAttributes="@(AssemblyAttributes)" />
</Target>
Điều này sẽ tạo ra một file CustomAssemblyInfo.cs trong thư mục của bạn "obj", có chứa một dòng duy nhất: [assembly: AssemblyMetadata("AssemblyDate", "DATE_OF_BUILD_HERE")]
tập tin này sẽ được biên dịch vào lắp ráp của bạn, vì vậy bạn có thể truy cập vào nó khi chạy sử dụng phản ánh, chẳng hạn như với đoạn mã sau:
using System;
using System.Linq;
using System.Reflection;
public class Application
{
static DateTime BuildDate;
public static DateTime GetBuildDate()
{
if (BuildDate == default(DateTime)) {
var attr = typeof(Application).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>();
var dateStr = attr.Single(a => a.Key == "AssemblyDate")?.Value;
BuildDate = DateTime.Parse(dateStr);
}
return BuildDate;
}
}
Một điều cần lưu ý, AssemblyMetadataAttribute mà tôi đang sử dụng ở đây là chỉ được thêm vào .NET 4.5.3, vì vậy nếu bạn cần hỗ trợ phiên bản trước đó, bạn có thể chỉ cần xác định loại thuộc tính tùy chỉnh của riêng mình để giữ giá trị ngày tháng.
Hãy coi chừng! Mã này không hoạt động khi bạn xây dựng một cái gì đó vào ngày 11 tháng 3 năm 2012 (vì năm nhuận?): Nó sẽ trở lại ngày 12 tháng 3 thay vì ngày 11 tháng 3 – JYL