Wednesday, October 08, 2008

MSDN Question: How do I access Assembly Information values set from Project Properties dialog?

I just came across this interesting question in WPF forum where a developer wanted to know if there is a straight-forward way to access the assembly information such as Title, Description, Version, etc. Note that when you set these values from Project Properties->Application->Assembly Information, they are added to AssemblyInfo.cs

So there has to be a way to access these at runtime.

Initially when I searched online to see what folks have to say about this, I came across a post where a MS employee!!! posted indirect ways to do that like writing a wrapper and using code generator to generate AssemblyInfo.cs from our custom class. Anyway, with simple concept of Assembly.GetExecutingAssembly() I could get what I wanted.

Then I noticed a method called GetCustomAttributes(true/false) which sounds interesting, especially when you look at segments of assemblyinfo.cs

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XamlDemystified")]
[assembly: AssemblyDescription("Read This!")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XamlDemystified")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

These are attributes so GetCustomAttributes() should return these values.

So, I tried to print each "Type" of attribute returned (It returns list of objects) as I wanted to know if there is a way that I could get the values. The output I noticed, when I ran from my application was:

So, if you want to display Description of the Assembly, you could do something like this:
foreach (var attr inAssembly.GetExecutingAssembly().GetCustomAttributes(true))
               AssemblyDescriptionAttribute ada = attr asAssemblyDescriptionAttribute;
               if(ada != null) Display(ada.Description);

So, it is not difficult after all!!

I hope this helps quiet a few.

No comments: