Saturday, March 22, 2008

Get assembly info about current C# application

Version information of an assembly is stored in the AssemblyInfo.cs file, which consists of Major Version, Minor Version, Build Number and Revision details. You can access the assembly information using different methods.

1. To get the assembly version (AssemblyVersion in AssemblyInfo file), use the following line of code.

System.Reflection.Assembly.GetExecutingAssembly().GetName().Version

2. To obtain the file version number (AssemblyFileVersion in AssemblyInfo file), the following block of code can be used.

System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion)

3. The GetCustomAttributes() can be used to obtain detailed information about the Assembly. The following block of code can be used to obtain the version information of the executing assembly.

object assemblyObjects = Assembly.GetEntryAssembly().GetCustomAttributes( (typeof(AssemblyFileVersionAttribute)), true);
if (assemblyObjects.Length > 0)
     MessageBox.Show(((AssemblyFileVersionAttribute)assemblyObjects[0]).Version);

The AssemblyFileVersionAttribute class is inside the System.Reflection namespace. You can obtain the complete set of attribute information, by passing just a boolean value to the GetCustomAttributes function (ie. by avoiding the specific Type information. This function has 2 overloads).
A function can be written using Generics, for extracting any required attribute information from the assembly. Basic version of such a function is given below.

public static T GetAssemblyAttribute<T>(Assembly assembly) where T : Attribute
{
    if (assembly == null)
        return null;

    object[] attributes = assembly.GetCustomAttributes(typeof(T), true);

    if (attributes == null)
        return null;

    if (attributes.Length == 0)
       return null;

    return (T)attributes[0];
}

The function can be invoked as follows.

AssemblyFileVersionAttribute fileInfo = GetAssemblyAttribute<AssemblyFileVersionAttribute>(Assembly.GetEntryAssembly())

No comments: