You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#控制台应用运行时修改程序集描述?

在C#控制台应用运行时修改程序集描述信息的解决方案

首先明确:运行时无法直接修改当前正在执行的程序集的AssemblyDescription属性——这些元数据是编译时写入PE文件的,程序加载后会被操作系统标记为只读,且CLR会锁定程序集文件,无法直接修改。

以下是几种可行的替代方案:

1. 动态维护描述信息(推荐)

放弃依赖编译时的[assembly: AssemblyDescription("")],转而自己维护一个可动态修改的描述字段,在需要展示时读取这个动态值即可。

示例代码:

// 全局维护动态描述信息
public static class AppRuntimeInfo
{
    public static string CurrentAssemblyDescription { get; set; } = "默认程序集描述";
}

// 调用示例
Console.WriteLine("当前描述:" + AppRuntimeInfo.CurrentAssemblyDescription);
// 运行时修改
AppRuntimeInfo.CurrentAssemblyDescription = "运行时更新后的新描述";
Console.WriteLine("更新后描述:" + AppRuntimeInfo.CurrentAssemblyDescription);

2. 修改磁盘上未加载的程序集的描述信息

如果需要修改的是未被当前进程加载的其他程序集的描述,可以借助Mono.Cecil库编辑程序集的元数据。

步骤:

  1. 安装NuGet包:Install-Package Mono.Cecil
  2. 使用以下代码修改目标程序集:
using Mono.Cecil;

var targetAssemblyPath = @"D:\UnloadedAssembly.dll";
// 读取目标程序集
var assemblyDef = AssemblyDefinition.ReadAssembly(targetAssemblyPath);

// 查找AssemblyDescriptionAttribute
var descriptionAttr = assemblyDef.CustomAttributes.FirstOrDefault(attr => 
    attr.AttributeType.FullName == "System.Reflection.AssemblyDescriptionAttribute");

if (descriptionAttr != null)
{
    // 替换现有描述
    descriptionAttr.ConstructorArguments[0] = new CustomAttributeArgument(
        assemblyDef.MainModule.TypeSystem.String, "修改后的程序集描述");
}
else
{
    // 不存在则添加新属性
    var attrType = assemblyDef.MainModule.ImportReference(typeof(System.Reflection.AssemblyDescriptionAttribute));
    var ctor = assemblyDef.MainModule.ImportReference(attrType.GetConstructor(new[] { typeof(string) }));
    assemblyDef.CustomAttributes.Add(new CustomAttribute(ctor)
    {
        ConstructorArguments = { new CustomAttributeArgument(assemblyDef.MainModule.TypeSystem.String, "新增的程序集描述") }
    });
}

// 保存修改
assemblyDef.Write(targetAssemblyPath);

注意:

  • 该方法仅适用于未被加载的程序集,当前正在运行的程序集因被CLR锁定无法修改。
  • .NET Core/.NET 5+已移除AppDomain卸载功能,无法通过卸载当前程序集再修改的方式实现自我更新。

内容的提问来源于stack exchange,提问作者Daud Raza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:45:48