.net 如何读取程序集属性

vhmi4jdf  于 2023-03-09  发布在  .NET
关注(0)|答案(8)|浏览(133)

在我的程序中,如何读取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("")]

我想向我的程序的用户显示其中的一些值,所以我想知道如何从主程序和我正在使用的组件程序集加载它们。

zzoitvuj

zzoitvuj1#

这相当简单。你必须使用反射。你需要一个Assembly的示例来表示你想要读取的具有属性的程序集。一个简单的方法是:

typeof(MyTypeInAssembly).Assembly

然后您可以执行以下操作,例如:

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

AssemblyProductAttribute attribute = null;
if (attributes.Length > 0)
{
   attribute = attributes[0] as AssemblyProductAttribute;
}

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

mrzz3bfm

mrzz3bfm2#

我创建了这个使用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();
}

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

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

r7knjye23#

好吧,也许现在有点过时的原始问题,但我会提出这一点,以供未来参考无论如何。
如果要从组件本身内部执行此操作,请使用以下命令:

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

object[] customAttributes = this.GetType().Assembly.GetCustomAttributes(false);

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

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

  if (attribute.GetType() == typeof(GuidAttribute))
  {
    assemblyGuid = ((GuidAttribute) attribute).Value;
    break;
  }
}
li9yvcax

li9yvcax4#

好吧,我尝试了很多资源来寻找一种方法来提取Assembly.LoadFrom(path)的.dll属性。但不幸的是,我找不到任何好的资源。而这个问题是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();
        }
    }
}

样本输出:

Name : AssemblyTitleAttribute
   >> Value : "My Product"
yjghlzjz

yjghlzjz5#

我个人非常喜欢lance Larsen and his static AssemblyInfo class的实现。
基本上就是将类粘贴到程序集中(我通常使用已经存在的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);
    }
}

使用System添加;到文件的顶部,你就可以开始了
对于我的应用程序,我使用这个类来设置/获取/使用我的本地用户设置:

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;
}

看看拉森斯的网站(MVP),他有很酷的东西来获得灵感。

0mkxixxg

0mkxixxg6#

我用这个:

public static string Title
{
    get
    {
        return GetCustomAttribute<AssemblyTitleAttribute>(a => a.Title);
    }
}

供参考:

using System;
using System.Reflection;
using System.Runtime.CompilerServices;


namespace Extensions
{

    public static class AssemblyInfo
    {

        private static Assembly m_assembly;

        static AssemblyInfo()
        {
            m_assembly = Assembly.GetEntryAssembly();
        }

        public static void Configure(Assembly ass)
        {
            m_assembly = ass;
        }

        public static T GetCustomAttribute<T>() where T : Attribute
        {
            object[] customAttributes = m_assembly.GetCustomAttributes(typeof(T), false);
            if (customAttributes.Length != 0)
            {
                return (T)((object)customAttributes[0]);
            }
            return default(T);
        }

        public static string GetCustomAttribute<T>(Func<T, string> getProperty) where T : Attribute
        {
            T customAttribute = GetCustomAttribute<T>();
            if (customAttribute != null)
            {
                return getProperty(customAttribute);
            }
            return null;
        }

        public static int GetCustomAttribute<T>(Func<T, int> getProperty) where T : Attribute
        {
            T customAttribute = GetCustomAttribute<T>();
            if (customAttribute != null)
            {
                return getProperty(customAttribute);
            }
            return 0;
        }


        public static Version Version
        {
            get
            {
                return m_assembly.GetName().Version;
            }
        }

        public static string Title
        {
            get
            {
                return GetCustomAttribute<AssemblyTitleAttribute>(
                    delegate(AssemblyTitleAttribute a)
                    {
                        return a.Title;
                    }
                );
            }
        }

        public static string Description
        {
            get
            {
                return GetCustomAttribute<AssemblyDescriptionAttribute>(
                    delegate(AssemblyDescriptionAttribute a)
                    {
                        return a.Description;
                    }
                );
            }
        }

        public static string Product
        {
            get
            {
                return GetCustomAttribute<AssemblyProductAttribute>(
                    delegate(AssemblyProductAttribute a)
                    {
                        return a.Product;
                    }
                );
            }
        }

        public static string Copyright
        {
            get
            {
                return GetCustomAttribute<AssemblyCopyrightAttribute>(
                    delegate(AssemblyCopyrightAttribute a)
                    {
                        return a.Copyright;
                    }
                );
            }
        }


        public static string Company
        {
            get
            {
                return GetCustomAttribute<AssemblyCompanyAttribute>(
                    delegate(AssemblyCompanyAttribute a)
                    {
                        return a.Company;
                    }
                );
            }
        }

        public static string InformationalVersion
        {
            get
            {
                return GetCustomAttribute<AssemblyInformationalVersionAttribute>(
                    delegate(AssemblyInformationalVersionAttribute a)
                    {
                        return a.InformationalVersion;
                    }
                );
            }
        }


        public static int ProductId
        {
            get
            {
                return GetCustomAttribute<AssemblyProductIdAttribute>(
                    delegate(AssemblyProductIdAttribute a)
                    {
                        return a.ProductId;
                    }
                );
            }
        }

        public static string Location
        {
            get
            {
                return m_assembly.Location;
            }
        }

    }

}
9wbgstp7

9wbgstp77#

如果您知道您要查找的属性是唯一的,那么使用Attribute类的这个经常被忽略的静态helper方法会容易得多:

var attribute = Attribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute))

这样做比较容易,因为你不需要去处理数组,也不需要担心那个讨厌的inherit参数,你只需要直接得到一个属性值,或者null(如果不存在的话)。

yrefmtwq

yrefmtwq8#

这是在一行代码中检索特定属性的好方法。不需要特殊的类。

string company = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false)).Company;

相关问题