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

Visual Studio 2022中CSPROJ AssemblyAttribute显示文件缺失问题

解决.NET Framework 4.8中自定义AssemblyAttribute无法识别及读取的问题

1. 确保自定义属性类的正确实现

自定义属性必须是public密封类,继承自Attribute,并指定正确的AttributeUsage,且构造函数参数需为字符串类型(因为MSBuild仅支持传递字符串参数到程序集属性):

using System;

[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
public sealed class BuiltDateAttribute : Attribute
{
    public DateTime BuiltDate { get; }

    // 必须接收字符串参数,MSBuild无法直接传递DateTime类型
    public BuiltDateAttribute(string builtDate)
    {
        if (DateTime.TryParse(builtDate, out var date))
        {
            BuiltDate = date;
        }
        else
        {
            throw new ArgumentException("无效的日期格式", nameof(builtDate));
        }
    }
}

2. 修正.csproj中的AssemblyAttribute配置

.NET Framework项目与.NET Core/.NET 5+的MSBuild语法有差异,需使用_ParameterN传递构造函数参数,而非博客中的Arguments:

<PropertyGroup>
    <!-- 生成UTC格式的构建时间字符串,避免时区问题 -->
    <BuiltDate>$([System.DateTime]::UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"))</BuiltDate>
</PropertyGroup>

<ItemGroup>
    <!-- 替换YourNamespace为属性类实际的命名空间 -->
    <AssemblyAttribute Include="YourNamespace.BuiltDateAttribute">
        <_Parameter1>$(BuiltDate)</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

3. 消除VS解决方案管理器的“缺失文件”提示

这是VS缓存异常导致的,可通过以下方式修复:

  • 右键项目 → 卸载项目 → 右键重新加载项目;
  • 关闭VS,删除项目根目录下的隐藏.vs文件夹,再重新打开解决方案。

4. 正确读取程序集属性的代码

确保从目标程序集获取属性,并引用正确的命名空间:

using System;
using System.Reflection;
using YourNamespace; // 替换为属性类所在的命名空间

var targetAssembly = Assembly.GetExecutingAssembly(); // 或Assembly.GetAssembly(typeof(YourType))
var builtDateAttribute = targetAssembly.GetCustomAttribute<BuiltDateAttribute>();

if (builtDateAttribute != null)
{
    Console.WriteLine($"程序集构建时间:{builtDateAttribute.BuiltDate:yyyy-MM-dd HH:mm:ss}");
}

额外排查步骤

  • 若属性类在类库项目中,确认主项目已正确引用该类库;
  • 用ILSpy等反编译工具查看输出程序集,检查BuiltDateAttribute是否已被嵌入;
  • 确认项目属性中“MSBuild工具版本”与VS版本匹配(17.9.6对应MSBuild 17.9.x)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:25:07