Wednesday, February 14, 2007

Getting the Version of a .NET Assembly at Runtime

The versions of all .NET assemblies are commonly located in the AssemblyInfo.cs file in each project. This can be extracted via code for use during execution and can easily be used to display version information on an About Box, for example.

Getting the version as a string is as straightfoward as the following code:

string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

The GetExecutingAssembly() method returns the Assembly of the executable that the code is running in. Other methods allow you to get the calling assembly or the Assembly containing a particular Type.

The GetName() method call returns an AssemblyName object, which provides information the assembly's unique identity, including the version, version compatibility, culture information and full name.

The Version property returns a Version object, providing access to the individual elements of the version (major, minor, revision, etc). It also provides overloads for comparison with other Version objects.

No comments: