2008-10-09 43 views
52

Trong chương trình của tôi, làm sao tôi có thể đọc các thuộc tính thiết lập trong AssemblyInfo.cs:Làm thế nào để đọc lắp ráp thuộc tính

[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("")] 

Tôi muốn hiển thị một số các giá trị cho người sử dụng chương trình của tôi, vì vậy tôi Tôi muốn biết làm thế nào để tải chúng từ chương trình chính và từ các hội đồng komponent tôi đang sử dụng.

Trả lời

51

Điều này là hợp lý dễ dàng. Bạn phải sử dụng sự phản chiếu. Bạn cần một thể hiện của Assembly đại diện cho assembly với các thuộc tính mà bạn muốn đọc. Một cách dễ dàng để nhận này là để làm:

typeof(MyTypeInAssembly).Assembly 

Sau đó, bạn có thể làm được điều này, ví dụ:

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

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

Tham khảo attribute.Product bây giờ sẽ cung cấp cho bạn những giá trị mà bạn truyền cho các thuộc tính trong AssemblyInfo của bạn. cs. Tất nhiên, nếu thuộc tính bạn tìm kiếm có thể xảy ra nhiều lần, bạn có thể nhận được nhiều cá thể trong mảng được trả về bởi GetCustomAttributes, nhưng điều này thường không phải là vấn đề cho các thuộc tính mức lắp ráp giống như những thuộc tính bạn muốn truy xuất.

+4

Bạn cũng có thể sử dụng Assembly.GetExecutingAssembly() GetCustomAttributes() để lấy các thuộc tính của assembly đang thực hiện. – jop

+0

Lưu ý rằng nếu bạn đang đọc thuộc tính cho một hội đồng không được tải, quá trình tải không thể hoàn tác trừ khi một AppDomain riêng biệt được sử dụng và sau đó được tải xuống. –

+4

GetExecutingAssembly không phải lúc nào cũng cung cấp những gì bạn muốn (ví dụ, nó có thể trả về trình gỡ lỗi nếu trình gỡ rối khởi động ứng dụng của bạn). –

10

Ok, có lẽ một chút lỗi thời cho câu hỏi ban đầu nhưng tôi sẽ trình bày điều này để tham khảo trong tương lai.

Nếu bạn muốn làm điều đó từ bên trong lắp ráp tự sau đó sử dụng như sau:

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

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

Sau đó bạn có thể lặp qua tất cả các thuộc tính tuỳ chỉnh để tìm ra một (s) bạn cần ví dụ

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

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

Tôi muốn sử dụng Bản quyền. Nó không có trong danh sách các thuộc tính song song với GuidAttribute tại http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.aspx – AnneTheAgile

+0

(xin lỗi, không thể chỉnh sửa bình luận khác của tôi) Điều này thật tuyệt, Tôi thấy System.Reflection.Assembly * có tất cả các thuộc tính thông thường và nhiều thuộc tính mà tôi chưa biết. http://msdn.microsoft.com/en-us/library/system.attribute.aspx Để sử dụng Bản quyền, tác phẩm này đã hoạt động; aCopyright = ((thuộc tính AssemblyCopyrightAttribute)) .Copyright.ToString(); – AnneTheAgile

12

tôi đã tạo ra phương pháp mở rộng này có sử dụng 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(); 
} 

và sau đó bạn có thể thoải mái sử dụng nó như thế:

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

Một phương pháp tiện ích tuyệt vời. Một gợi ý nhanh chóng cho những người quan tâm đến việc có được phiên bản của một hội đồng. Sử dụng: assembly.GetAssemblyAttribute () (chi tiết: http://stackoverflow.com/questions/1144525/getcustomattribute-returns-null-for-assemblyversionattribute) – xDisruptor

4

Được rồi, tôi đang cố gắng để đi thông qua nhiều tài nguyên để tìm phương pháp trích xuất thuộc tính .dll cho một số Assembly.LoadFrom(path). Nhưng tiếc là tôi không thể tìm thấy bất kỳ tài nguyên tốt. Và câu hỏi này là kết quả hàng đầu nhất cho việc tìm kiếm trên c# get assembly attributes (Đối với tôi ít nhất) Vì vậy, tôi nghĩ đến việc chia sẻ công việc của tôi.

Tôi đã viết theo Chương trình Console đơn giản để lấy các thuộc tính lắp ráp chung sau nhiều giờ đấu tranh. Ở đây tôi đã cung cấp mã để mọi người có thể sử dụng nó để tham khảo thêm.

Tôi sử dụng CustomAttributes thuộc tính cho việc này.Cảm thấy tự do để nhận xét về phương pháp này

Code:

using System; 
using System.Reflection; 

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

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

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

      Console.ReadKey(); 
     } 
    } 
} 

Sample Output:

Name : AssemblyTitleAttribute 
    >> Value : "My Product" 
+1

Tôi sẽ chỉ ra rằng thuộc tính ['CustomAttributes'] (https : //msdn.microsoft.com/en-us/library/system.reflection.assembly.customattributes%28v=vs.110%29.aspx) chỉ khả dụng từ .NET 4.5 trở lên. Trong .NET 4.0 trở lên, phương thức ['GetCustomAttributesData()'] (https://msdn.microsoft.com/en-us/library/system.reflection.assembly.getcustomattributesdata%28v=vs.100%29.aspx) có sẵn như là một thay thế. –

2

tôi sử dụng này:

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

để tham khảo:

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

    } 

} 
+0

public int tĩnh ProductID { được { trở GetCustomAttribute ( đại biểu (AssemblyProductIdAttribute a) { trở a.ProductId; } ); } } Ở đây, 'AssemblyProductIdAttribute 'Lỗi -> Không thể tìm thấy loại hoặc không gian tên' AssemblyProductIdAttribute '(bạn đang thiếu một chỉ thị sử dụng hoặc tham chiếu assembly?) – Pritam

+0

Pritam: Bạn đang thiếu hệ thống không gian tên. Phản ánh (bằng cách sử dụng System.Reflection;) hoặc bạn đang sử dụng phiên bản/phiên bản khung hình lẻ. https://msdn.microsoft.com/en-us/library/system.reflection.assemblyproductattribute(v=vs.110).aspx –

+0

__using System.Reflection__ được bao gồm trong mã, tôi có thể dễ dàng sử dụng các chức năng khác. Không ai trong số họ đưa ra bất kỳ lỗi nào. Ngoài ra, Framework cũng chính xác. – Pritam

Các vấn đề liên quan