开发者

Retrieve AssemblyCompanyName from Class Library

I would like to get the AssemblyCompany attribute from a WinForm project 开发者_开发技巧inside of my C# class library. In WinForms, I can get to this information by using:

Application.CompanyName;

However, I can't seem to find a way to get at that same information using a class library. Any help you could provide would be great!


To get the assembly in which your current code (the class library code) actually resides, and read its company attribute:

Assembly currentAssem = typeof(CurrentClass).Assembly;
object[] attribs = currentAssem.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
if(attribs.Length > 0)
{
    string company = ((AssemblyCompanyAttribute)attribs[0]).Company
}


You could use the FileVersionInfo class to get CompanyName and much more.

Dim info = FileVersionInfo.GetVersionInfo(GetType(AboutPage).Assembly.Location)
Dim companyName = info.CompanyName
Dim copyright = info.LegalCopyright
Dim fileVersion = info.FileVersion


Assembly assembly = typeof(CurrentClass).GetAssembly();
AssemblyCompanyAttribute companyAttribute = AssemblyCompanyAttribute.GetCustomAttribute(assembly, typeof(AssemblyCompanyAttribute)) as AssemblyCompanyAttribute;
if (companyAttribute != null)
{
    string companyName = companyAttribute.Company;
    // Do something
}


The dotnet 5 version:

typeof(CurrentClass).GetCustomAttribute<AssemblyCompanyAttribute>().Company


You can also get it using LINQ :

public static string GetAssemblyCompany<T>(){
    string company = (from Attribute a in (typeof(T).Assembly.GetCustomAttributes())
        where a is AssemblyCompanyAttribute
        select ((AssemblyCompanyAttribute)a).Company).FirstOrDefault();

    return company;
}


This is a great way to get what you are looking for in a single line:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜