views:

1553

answers:

3

In my program, how can I read the properties set in 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("")]

I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using.

A: 

Have you tried:

http://msdn.microsoft.com/en-us/library/hk0t7cax.aspx

The Assembly class should provide you the info you want.

mspmsp
+10  A: 

This is reasonably easy. You have to use reflection. You need an instance of Assembly that represents the assembly with the attributes you want to read. An easy way of getting this is to do:

typeof(MyTypeInAssembly).GetAssembly()

Then you can do this, for example:

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

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

Referencing attribute.Product will now give you the value you passed to the attribute in your AssemblyInfo.cs. Of course, if the attribute you look for can occur more than once, you may get multiple instances in the array returned by GetCustomAttributes, but this is not usually an issue for assembly level attributes like the ones you hope to retrieve.

Jeff Yates
You can also use Assembly.GetExecutingAssembly().GetCustomAttributes() to get the attributes of the currently executing assembly.
jop
Note that if you're reading attributes for an assembly that isn't loaded, the process of loading cannot be undone unless a separate AppDomain is used and then unloaded.
Drew Noakes
GetExecutingAssembly doesn't always give what you want (for example, it can return the debugger if the debugger started your application).
Jeff Yates
+2  A: 

Ok, perhaps a bit out of date now for the original question but I will present this for future reference anyway.

If you want to do it from inside the assembly itself then use the following :

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

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

You can then iterate through all of the custom attributes to find the one(s) you require e.g.

foreach (object attribute in customAttributes) { string assemblyGuid = string.Empty;
if (attribute.GetType() == typeof(GuidAttribute)) { assemblyGuid = ((GuidAttribute) attribute).Value; break; } }