quick question. I want to find out if a DLL is present in the system where my application is executing.
Is this possible in C#? (in a way that would work on ALL Windows OS?)
For DLL i mean a non-.NET classic dll (a Win32 dll)
(Basically I want to make a check cause I'm using a DLL that may or may not be present on the user system, but I don't want the app to crash without warning when this is not present :P)
Actually it does not throw FileNotFoundException.
Also for that one needs to check in multiple places for path, for the LoadLibrary
There is a standard exception in .net the is derived from TypeLoadException, that is DllNotFoundException.
Best way is to wrap a method/PInvoke call in try..catch and handle the DllNotFoundException since .net will check for application path as well as any other paths set as part of PATH OS Environment variable.
Call LoadLibrary.
http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx
When using platform invoke calls in .NET, you could use
Marshal.PrelinkAll(Type)
methodAs you can see, it performs additional checks other than if the dll exists, like locating the entry points (e.g if
SomeMethod()
andSomeMethod2()
actually exist in the process like in the following code).Then use
try...catch
strategy to perform your check:I think it is better to call GetModuleHandle rather than LoadLibrary to check if a dll is loaded.
I would avoid calling LoadLibrary to check the presence of a dll. LoadLibrary will load the dll into the address space and load other modules as necessary. Assuming you don't need to actually use the dll, I'd stick with GetModuleHandle.
Call the
LoadLibrary
API function:I'm assuming this is a PInvoke call?
If so the easiest way to make this determine if it's present is to make the call and catch the exception that results if the file does not exist.