如何阅读程序集属性

Sam*_*Sam 57 .net reflection attributes assemblies

在我的程序中,如何读取AssemblyInfo.cs中设置的属性:

[assembly: AssemblyTitle("My Product")]
[assembly: AssemblyDescription("...")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Radeldudel inc.")]
[assembly: AssemblyProduct("My Product")]
[assembly: AssemblyCopyright("Copyright @ me 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
Run Code Online (Sandbox Code Playgroud)

我想向我的程序用户显示一些这些值,所以我想知道如何从主程序和我正在使用的komponent程序集加载它们.

Jef*_*tes 59

这相当容易.你必须使用反射.您需要一个Assembly实例,它表示具有您要读取的属性的程序集.获得这个的简单方法是:

typeof(MyTypeInAssembly).Assembly
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做,例如:

object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);

AssemblyProductAttribute attribute = null;
if (attributes.Length > 0)
{
   attribute = attributes[0] as AssemblyProductAttribute;
}
Run Code Online (Sandbox Code Playgroud)

attribute.Product现在,引用将为您提供传递给AssemblyInfo.cs中的属性的值.当然,如果您查找的属性可能出现多次,您可能会在GetCustomAttributes返回的数组中获得多个实例,但这通常不是您希望检索的程序集级别属性的问题.

  • 您还可以使用Assembly.GetExecutingAssembly().GetCustomAttributes()来获取当前正在执行的程序集的属性. (4认同)
  • GetExecutingAssembly并不总能提供您想要的内容(例如,如果调试器启动了您的应用程序,它可以返回调试器). (4认同)

dmi*_*scu 13

我创建了这个使用Linq的扩展方法:

public static T GetAssemblyAttribute<T>(this System.Reflection.Assembly ass) where T :  Attribute
{
    object[] attributes = ass.GetCustomAttributes(typeof(T), false);
    if (attributes == null || attributes.Length == 0)
        return null;
    return attributes.OfType<T>().SingleOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以方便地使用它:

var attr = targetAssembly.GetAssemblyAttribute<AssemblyDescriptionAttribute>();
if(attr != null)
     Console.WriteLine("{0} Assembly Description:{1}", Environment.NewLine, attr.Description);
Run Code Online (Sandbox Code Playgroud)


小智 10

好吧,对于原始问题,现在可能有点过时,但无论如何我将提供此信息以供将来参考.

如果要从程序集内部执行此操作,请使用以下命令:

using System.Runtime.InteropServices;
using System.Reflection;

object[] customAttributes = this.GetType().Assembly.GetCustomAttributes(false);
Run Code Online (Sandbox Code Playgroud)

然后,您可以遍历所有自定义属性以查找所需的属性,例如

foreach (object attribute in customAttributes)
{
  string assemblyGuid = string.Empty;    

  if (attribute.GetType() == typeof(GuidAttribute))
  {
    assemblyGuid = ((GuidAttribute) attribute).Value;
    break;
  }
}
Run Code Online (Sandbox Code Playgroud)


Kav*_*uwa 6

好的,我试图通过许多资源找到一种方法来提取 .dll 文件的 .dll 属性Assembly.LoadFrom(path)。但不幸的是我找不到任何好的资源。这个问题是搜索的最高结果c# get assembly attributes(至少对我来说)所以我想分享我的工作。

经过数小时的努力,我编写了以下简单的控制台程序来检索常规程序集属性。我在这里提供了代码,以便任何人都可以将其用于进一步的参考工作。

CustomAttributes为此使用财产。随意评论这种方法

代码 :

using System;
using System.Reflection;

namespace MetaGetter
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.LoadFrom("Path to assembly");

            foreach (CustomAttributeData attributedata in assembly.CustomAttributes)
            {
                Console.WriteLine(" Name : {0}",attributedata.AttributeType.Name);

                foreach (CustomAttributeTypedArgument argumentset in attributedata.ConstructorArguments)
                {
                    Console.WriteLine("   >> Value : {0} \n" ,argumentset.Value);
                }
            }

            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例输出:

Name : AssemblyTitleAttribute
   >> Value : "My Product"
Run Code Online (Sandbox Code Playgroud)


PPa*_*ann 5

我个人非常喜欢lance Larsen 和他的静态 AssemblyInfo 类的实现

一个人基本上将类粘贴到他的程序集中(我通常使用已经存在的 AssemblyInfo.cs 文件,因为它符合命名约定)

要粘贴的代码是:

internal static class AssemblyInfo
{
    public static string Company { get { return GetExecutingAssemblyAttribute<AssemblyCompanyAttribute>(a => a.Company); } }
    public static string Product { get { return GetExecutingAssemblyAttribute<AssemblyProductAttribute>(a => a.Product); } }
    public static string Copyright { get { return GetExecutingAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright); } }
    public static string Trademark { get { return GetExecutingAssemblyAttribute<AssemblyTrademarkAttribute>(a => a.Trademark); } }
    public static string Title { get { return GetExecutingAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title); } }
    public static string Description { get { return GetExecutingAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description); } }
    public static string Configuration { get { return GetExecutingAssemblyAttribute<AssemblyConfigurationAttribute>(a => a.Configuration); } }
    public static string FileVersion { get { return GetExecutingAssemblyAttribute<AssemblyFileVersionAttribute>(a => a.Version); } }

    public static Version Version { get { return Assembly.GetExecutingAssembly().GetName().Version; } }
    public static string VersionFull { get { return Version.ToString(); } }
    public static string VersionMajor { get { return Version.Major.ToString(); } }
    public static string VersionMinor { get { return Version.Minor.ToString(); } }
    public static string VersionBuild { get { return Version.Build.ToString(); } }
    public static string VersionRevision { get { return Version.Revision.ToString(); } }

    private static string GetExecutingAssemblyAttribute<T>(Func<T, string> value) where T : Attribute
    {
        T attribute = (T)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(T));
        return value.Invoke(attribute);
    }
}
Run Code Online (Sandbox Code Playgroud)

您添加一个使用系统;到文件的顶部,你就可以开始了。

对于我的应用程序,我使用这个类来设置/获取/使用我的本地用户设置:

internal class ApplicationData
{

    DirectoryInfo roamingDataFolder;
    DirectoryInfo localDataFolder;
    DirectoryInfo appDataFolder;

    public ApplicationData()
    {
        appDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyInfo.Product,"Data"));
        roamingDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),AssemblyInfo.Product));
        localDataFolder   = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyInfo.Product));

        if (!roamingDataFolder.Exists)            
            roamingDataFolder.Create();

        if (!localDataFolder.Exists)
            localDataFolder.Create();
        if (!appDataFolder.Exists)
            appDataFolder.Create();

    }

    /// <summary>
    /// Gets the roaming application folder location.
    /// </summary>
    /// <value>The roaming data directory.</value>
    public DirectoryInfo RoamingDataFolder => roamingDataFolder;


    /// <summary>
    /// Gets the local application folder location.
    /// </summary>
    /// <value>The local data directory.</value>
    public DirectoryInfo LocalDataFolder => localDataFolder;

    /// <summary>
    /// Gets the local data folder location.
    /// </summary>
    /// <value>The local data directory.</value>
    public DirectoryInfo AppDataFolder => appDataFolder;
}
Run Code Online (Sandbox Code Playgroud)

看看 Larsens 网站 (MVP),他有很酷的东西可以从中汲取灵感。