views:

109

answers:

3

I have a situation where I am using a third party library. On machines where the library is not installed, I am getting the excption: Unable to load DLL '*.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E). However, I am wrapping the calling code in a try-catch block.

I have tried catching both Exception and DllNotFoundException and neither actually catch the error. The app then closes ungracefully.

I would like for the app to catch the error, then continue without using the third-party functionality.

How can I either prevent the error with a dll check (without knowing the path) or gracefully catch the error.

Edit: More Details This is a third party app that allows me to use a usb device. They have provided a .net wrapper for their un-managed api (I think). I added the managed dll's to the project in the normal fashion.

Edit: I managed to get a path for the dll in question. I am doing a File.Exisits on the dll and not entering th code block if the dll does not exist. This seems to be working so far. Thanks for the help!

+4  A: 

The exception is being thrown in the JITter, not in your code (i.e., on a different thread). That means you're butter-side-down on this one.

Will
+1  A: 

The JITter throwing the exception makes this a bit tricky.

You can check for the dll, but you have to keep in mind when the JITter is going to look for the dll to load.

You MUST check for the dll before you load any types that depend on that dll. Loading the types happens whenever you hit a method that calls any types that require that type. (wow!). So basically you need to make sure that you don't call any methods that are contained in types that call methods that require your third-party library.

What I've done for saftey is: wrap any references to the DLL in a type that is never accessed or referenced directly - let's say this is WrapperClass. Check for the existance of the DLL, then (if it exists), use Activator.CreateInstance(...) to create an instance of WrapperClass.

Note that this is working for me up until .net 3.5. As far as I know, there is no guarantee this will not be broken in future versions, or even by hotfixes.

Philip Rieck
+1  A: 

You don't say how you are importing this third party library? Did you add it to your project and let VS create the wrapper for you automatically?

Or are you using DLLImport:

[DllImport("thirdParty.dll")]
static extern int thirdPartyFunction(some params);

Either way both of these methods aren't going to show you much love if the thirdParty.dll isn't installed on the machine.

You need to do what is called LateBinding check out this CodeProject article on how to do Late binding on native DLLs with C#

ParmesanCodice