Tony
Tony

Reputation: 12695

.NET Core 3.1 read Assembly's File Version

in my console app, I need to load the File Version value of some external assembly.

var assembly1 = Assembly.LoadFrom("my.dll");
var assembly2 = AssemblyLoadContext.Default.LoadFromAssemblyPath("my.dll");

var versionNumber = assembly1.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;

and here's the thing - if I use the var assembly1 = ... or var assembly2 = ... then I get the nasty error message

Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

when invoking the GetCustomAttribute method, but if the both lines are being used, then everything works fine. So, how to fix it to be able to use the var assembly1 = ... or var assembly2 = ... ?

Upvotes: 1

Views: 1597

Answers (2)

Huei Feng
Huei Feng

Reputation: 28

the following code is normal, please check the path is correct.

 private const string AssemblyPath = "C:\\Users\\test.dll";
 var assembly2 = AssemblyLoadContext.Default.LoadFromAssemblyPath(AssemblyPath);
 var versionNumber = assembly2.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;

or

 private const string AssemblyPath = "C:\\Users\\test.dll";
var assembly1 = Assembly.LoadFrom(AssemblyPath);
var versionNumber = assembly1.GetCustomAttribute<AssemblyFileVersionAttribute>().Version;

Upvotes: 0

mm8
mm8

Reputation: 169220

FileVersionInfo.GetVersionInfo doesn't try the load the entire DLL into the app:

System.Diagnostics.FileVersionInfo fvo = 
    System.Diagnostics.FileVersionInfo.GetVersionInfo(@"my.dll");

string versionNumber = fvo.FileVersion;

If you build my.dll with dotnet build -p:Version=4.4.4, versionNumber will be equal to "4.4.4.0" in the above sample code.

Upvotes: 4

Related Questions