.NET Core 6应用中如何获取程序GUID及程序集属性?
.NET Core/.NET 5+ 中获取程序集GUID及元数据的解决方案
在.NET Framework中使用的程序集属性获取代码在.NET Core/.NET 5+中失效,主要原因是Assembly.GetEntryAssembly()在部分场景返回null,且.NET Core项目的属性配置方式与.NET Framework不同,以下是可行的实现方案:
一、获取程序集GUID
方案1:获取当前执行程序集的GUID
using System; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; public static string GetAssemblyGuid() { var assembly = Assembly.GetExecutingAssembly(); var guidAttribute = assembly.GetCustomAttributes<GuidAttribute>().FirstOrDefault(); return guidAttribute?.Value ?? string.Empty; }
方案2:获取入口程序集的GUID
如果明确需要入口程序集的GUID,需先判断入口程序集是否存在:
public static string GetEntryAssemblyGuid() { var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) return string.Empty; var guidAttribute = entryAssembly.GetCustomAttributes<GuidAttribute>().FirstOrDefault(); return guidAttribute?.Value ?? string.Empty; }
二、获取公司等程序集元数据
简化代码实现,直接读取对应属性:
using System.Linq; using System.Reflection; public static string GetAssemblyCompany() { var assembly = Assembly.GetExecutingAssembly(); var companyAttribute = assembly.GetCustomAttributes<AssemblyCompanyAttribute>().FirstOrDefault(); return companyAttribute?.Company ?? string.Empty; }
同理,获取产品、版权等信息只需替换对应的Attribute类型,比如AssemblyProductAttribute、AssemblyCopyrightAttribute。
三、关键配置说明
.NET Core项目默认不会自动生成程序集GUID,需手动在.csproj文件中配置相关属性,否则无法获取到对应值:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <!-- 配置程序集GUID --> <Guid>你的GUID值</Guid> <!-- 配置公司信息 --> <Company>你的公司名称</Company> <!-- 其他可选元数据 --> <Product>产品名称</Product> <Copyright>版权信息</Copyright> </PropertyGroup> </Project>
注意事项
- 若在WinForms的.NET Core项目中使用,确保编译时这些属性已嵌入程序集;
- 避免在托管环境等特殊场景依赖
Assembly.GetEntryAssembly(),优先使用Assembly.GetExecutingAssembly()更可靠。
内容的提问来源于stack exchange,提问作者jstuardo
相关产品推荐
相关产品推荐

