Get the .NET assembly's AssemblyInformationalVersion value?

using System.Reflection.Assembly  
using System.Diagnostics.FileVersionInfo

// ...

public string GetInformationalVersion(Assembly assembly) {
    return FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
}

var attr = Assembly
    .GetEntryAssembly()
    .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) 
    as AssemblyInformationalVersionAttribute[];

It's an array of AssemblyInformationalVersionAttribute. It isn't ever null even if there are no attribute of the searched type.

var attr2 = Attribute
    .GetCustomAttribute(
        Assembly.GetEntryAssembly(), 
        typeof(AssemblyInformationalVersionAttribute)) 
    as AssemblyInformationalVersionAttribute;

This can be null if the attribute isn't present.

var attr3 = Attribute
    .GetCustomAttributes(
         Assembly.GetEntryAssembly(), 
         typeof(AssemblyInformationalVersionAttribute)) 
    as AssemblyInformationalVersionAttribute[];

Same as first.


Using a known type in your application you can simply do this:

using System.Reflection;

public static readonly string ProductVersion = typeof(MyKnownType).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;

Of course any process you use to get to the assembly your attribute is applied to is good. Note that this doesn't rely on System.Diagnostics or the WinForm's Application object.

Tags:

C#

.Net