Background
First of all, I did look elsewhere for a solution and found this solution, but this does not solve my issue.
I have an assembly referenced in my main project in Visual Studio, but I need to load it from outside my project, not in a sub-folder. I can load the assembly with the call…
System.Reflection.Assembly.LoadFrom(myExternalAssemblyPath);
…but the program will not run and gives me the following error:
FileNotFoundException was unhandled
Could not load file or assembly ‘MyAssembly, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=null’ or one of its dependencies. The
system cannot find the file specified.
I have no calls to the assembly before the call to load it, but the program still expects, even before it even enters the Main function apparently, that the DLL be in the program’s folder.
Quesiton:
How do I get my program to still reference this in Visual Studio, but load it from a different location when actually running the program? Is there a directive I need to specify somewhere to tell the program to wait to load it? Is there some other solution?
NOTE: I do not want to add the folder and DLL to the PATH variable. That is not a viable solution.
The trick is to implement the
AssemblyResolveevent on your application domain.http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx
This is where you help the runtime to locate assemblies which it tries to load and cannot find using the default searching strategy. This should be straightforward, the runtime will call your handler for each missing assembly and you just have to load it by yourself from the custom path and return from the handler.
An important point to remember: in .NET the JIT processes methods (into native code) fully before they are invoked. If your Main method uses any types or methods from the assembly you are trying to load, it won’t get as far as executing Main. Consequently, Main should only setup the assembly-loading. All other code (especially code relating to the assembly in question) must be moved to another method, so it gets JIT-ted separately.