Have you ever ran into an error message like this but the version you have is newer than the one shown?
'Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.'
You can fix it by adding a callback that is invoked when the system can’t find the exact version of the library.
In this example, I am targeting .NET Framework 4.7.2 and the nuget package that I’ve imported has a dependency on an older version of Json.NET and throws an error, however I need the newest version of Json.NET (I can’t have 2 versions in the same project), so I’m going to tell the runtime to just use the newer assembly that I have.
void Main(string[] args){
//add these two lines as well as the MyResolveEventHandler below
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
//this is the code that was throwing the exception
HttpClient client = new HttpClient();
client.BaseAddress = new System.Uri( "http://localhost");
var response = client.PostAsJsonAsync("/whatever/api", "whatever").Result; //this call will cause the FileNotFoundException because the nuget lib that implements PostAsJsonAsync references 6.0.0.0
}
private static System.Reflection.Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
if(args.Name.StartsWith("Newtonsoft.Json")) {
//you can pick any class that is in the Newtonsoft.Json.dll
return typeof(Newtonsoft.Json.JsonConverter).Assembly;
}
return null;
}
Note that using the newer version of the dll may not always work, in which case you can also load the assembly by file path.
return System.Reflection.Assembly.LoadFrom($@"C:\somepath\to\your.dll");
get yourself on the email list
comments powered by Disqus