Home > Software engineering >  How to call tool DLLs in C# when the DLL-path is different on the target PC?
How to call tool DLLs in C# when the DLL-path is different on the target PC?

Time:09-30

I might be a bit stupid, but I want to create a tool in Visual Studio in C# and want to call third party tools via their API-DLLs. The only topics I found here are dealing with one of the two methods that I already know:

  1. Compilation time: add a reference to "C:\FooTool\foo.dll" in my project "using fooToolNamespace.fooToolClass" in my code (compilation time) --> I can "naturally" use the classes of the DLL and will even get full IntelliSense support if a suiting XML-file is available with the DLL. Also compilation time checks will be done for my usage of the dll.

  2. Dynamic (run time): calling e.g. Assembly.LoadFile(@"C:\FooTool\foo.dll") and then using reflection on it to find functions, fields and so on --> no IntelliSense, no compilation time checks

So I actually have the DLL at hand and thus option 1) would be nice during development. But if my tool is used on a different PC, the third-party DLL might be in a different path there, e.g. "C:\foo\foo.dll" and "C:\bar\foo.dll". In my understanding using a copy of "foo.dll" will not work, because "foo.dll" might have dependencies, e.g. requiring other files of the FooTool-directory. Thus in my understanding I have to call the DLL which is "installed" to the target PC and not a local copy of it.

So can I somehow change the path where my tool accesses the "foo.dll" at runtime and still use method 1) during development? Or is there another way of doing things? Or am I just dumb and there is a simple solution for all this?

Thanks a lot for the help and have a great day

Janis

CodePudding user response:

To be able to use option 1 (a referenced DLL), you need to put the DLL somewhere "where your EXE (or, more precisely, the Assembly Resolver) can find it" on the customer's PC.

So where does the assembly resolver look for your DLL?

  1. In the directory where the EXE resides (for desktop/console applications) or the bin subdirectory (for web applications). Since you mention that your DLL requires other dependencies as well, you'd need to copy them to that location as well.

  2. The Global Assembly Cache (GAC). If your dependency supports this, installing it to the GAC ensures that it can be found by your application.

These two are the "supported" scenarios. There is also the possibility to tweak the assembly resolver to look into other directories as well, but that should be reserved for special cases where the other two options failed. (We had such a case and solved it with a custom AssemblyResolve handler on the application domain.)

  • Related