C# 程序发布时加入发布时间

1. 修改 .csproj 文件‌

在 中添加以下配置,利用 MSBuild 的时间函数生成时间戳:

复制代码
<PropertyGroup>
    <!-- 其他配置... -->
    <AssemblyMetadata Include="BuildTime" Value="$([System.DateTime]::Now.ToString('yyyy-MM-dd HH:mm:ss'))" />
</PropertyGroup>

注意‌:(\[System.DateTime\]::Now...) 是 MSBuild 的属性函数语法,能确保在编译时刻获取时间。如果使用的是较旧版本的 MSBuild 或特定 CI 环境,也可以使用 (DateTime) 变量(需确保格式正确,如 yyyy-MM-dd HH:mm:ss)。‌注意‌:(\[System.DateTime\]::Now...) 是 MSBuild 的属性函数语法,能确保在编译时刻获取时间。如果使用的是较旧版本的 MSBuild 或特定 CI 环境,也可以使用 (DateTime) 变量(需确保格式正确,如 yyyy-MM-dd HH:mm:ss)。

‌2. 在代码中读取
复制代码
using System;
using System.Reflection;
using System.Linq;

public static string GetBuildTime()
{
    var assembly = Assembly.GetExecutingAssembly();
    // 查找名为 "BuildTime" 的自定义元数据
    var attribute = assembly.GetCustomAttribute<AssemblyMetadataAttribute>();
    
    // 如果有多个元数据,可能需要筛选 Key
    var buildTimeAttr = assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
                                .FirstOrDefault(a => a.Key == "BuildTime");

    if (buildTimeAttr != null)
    {
        return buildTimeAttr.Value;
    }
    
    return "Unknown";
}

时间准确,反映实际编译时刻。

不依赖文件系统,不受部署方式(如 ZIP 解压、复制)影响。

适合 CI/CD 环境。

相关推荐
公子小六8 小时前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
三雷科技9 小时前
第6章第4节:自定义分词器
开发语言·c#
zhanghaha131410 小时前
C# 系列教程_12 字符串 string 保姆级系统教程(面向新手,大量示例 + 原理讲解)
开发语言·数据库·c#
Coder_Shenshen1 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
寂寞的船1 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
1-1=01 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
波力海苔夹心脆6753 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
AI导出鸭PC端3 天前
Perplexity批量导出没有PDF模式?AI导出鸭插件补上最后一块拼图
人工智能·pdf·c#·ai导出鸭
Risehuxyc3 天前
C# 选用更流行的语言版本
c#
淡海水4 天前
09-04-内存-Unity原生对象生命周期
unity·c#·游戏引擎·gc