I am finishing off building an mvc web application using .net core 2.0 with vs2017 on Win10.In writing an 'About' page I looked to put in the current project version number (at present still set at 1.0.0). I would have thought that pretty straightforward!
The only reference I could find suggested:
AppVersion = typeof(RuntimeEnvironment).GetTypeInfo ().Assembly
.GetCustomAttribute<AssemblyFileVersionAttribute> ().Version;
However, this returns, in my case, '4.6.25814.01' - not what is required.
Can anyone suggest how to retrieve the version in code, please?
I assume that I want the 'Package Version' but admit I am not clear on the distinction between/how one would use 'Package Version', 'Assembly Version' and 'Assembly File Version'.
When you call typeof(RuntimeEnvironment).Assembly
, you're querying the containing assembly of that type. In this case this would be System.Runtime.InteropServices.dll
or Microsoft.Dotnet.PlatformAbstractions.dll
, depending on the namespace you've imported.
To get the information of your own assembly, you could simply replace RuntimeEnvironment
with one of your own types, for example
var appVersion = typeof(Program).Assembly
.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
or even
var appVersion = typeof(HomeController).Assembly
.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;
This would return "6.6.7.0" if the Package version if your project is set as follows:
You were close!
Here you can find more information on reflection for .NET in general, but it should work fine for .NET Core.
Tried on version 2.0
using System.Reflection;
var appVersion = string.Empty;
var customAttribute = typeof(Program).Assembly.GetCustomAttributes(false).SingleOrDefault(o => o.GetType() == typeof(AssemblyFileVersionAttribute));
if (null != customAttribute)
{
if (customAttribute is AssemblyFileVersionAttribute)
{
var fileVersionAttribute = customAttribute as AssemblyFileVersionAttribute;
appVersion = fileVersionAttribute.Version;
}
}
AssemblyFileVersionAttribute type is in System.Reflection namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With