views:

158

answers:

3

Hi, 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)

+1  A: 

Call LoadLibrary.

http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx

Steven Sudit
Elaborate more on the subject?
feal87
+1  A: 

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.

[DllImport("some.dll")]
private static void SomeMethod();

public static void SomeMethodWrapper() {
  try {
    SomeMethod();
  } catch (FileNotFoundException) {
    // Do Nothing 
  }
}
JaredPar
Its not a simple single call, the first call may not be the same all the time. I need a check more "higher level"
feal87
+3  A: 

Call the LoadLibrary API function:

[DllImport("kernel32", SetLastError=true)]
static extern IntPtr LoadLibrary(string lpFileName);

static bool CheckLibrary(string fileName) {
    return LoadLibrary(fileName) == IntPtr.Zero;
}
SLaks
Just what I needed. Thanks.
feal87
sweet, this is useful.
Stan R.
@feal - Beware that this doesn't proof anything other than that the DLL failed to load. There are many reasons, a missing file is just one of them.
Hans Passant
That doesn't just check the library, it loads it and keeps it loaded. You have to manually FreeLibrary.
Steven Sudit
Well, the library would be loaded anyway ALWAYS by my app (as its used 100% by the app :D), so the freelibrary is unneeded i think.
feal87
feal87, just for clarification, how were you binding to the library previously? Were you calling LoadLibrary?
Steven Sudit
IMHO the FreeLibrary *is* needed - otherwise you leak a reference to the library. This might not matter now but in the future, someone's going to think that CheckLibrary has no side effects and it's going to burn you.
Larry Osterman
Larry is right, not to mention it'll put noise into your Application Verifier checks. You *are* using AppVerifier to check for bugs, right?? Right??
Paul Betts
"The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count. Calling the FreeLibrary or FreeLibraryAndExitThread function decrements the reference count. The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count)."Citation from MSDN, but anyway a freelibrary cost nothing. I'll add it :P
feal87
I tried for the fun of it AppVerifier. 0 Error and 2 warning. Both warning are caused by the Intel Graphic Driver. :P
feal87