Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the .NET assembly's AssemblyInformationalVersion value?

Tags:

c#

.net

What is the C# syntax for getting the assembly's AssemblyInformationalVersion attribute value at runtime? Example:

[assembly: AssemblyInformationalVersion("1.2.3.4")]

like image 662
lance Avatar asked Oct 14 '11 15:10

lance


3 Answers

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

// ...

public string GetInformationalVersion(Assembly assembly) {
    return FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
}
like image 177
lance Avatar answered Oct 22 '22 16:10

lance


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.

like image 45
xanatos Avatar answered Oct 22 '22 16:10

xanatos


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.

like image 21
Robb Vandaveer Avatar answered Oct 22 '22 18:10

Robb Vandaveer