Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a DLL is present in the system

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)

like image 851
feal87 Avatar asked Feb 18 '10 22:02

feal87


2 Answers

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;
}
like image 106
SLaks Avatar answered Oct 07 '22 21:10

SLaks


When using platform invoke calls in .NET, you could use the Marshal.PrelinkAll(Type) method:

Setup tasks provide early initialization and are performed automatically when the target method is invoked. First-time tasks include the following:

Verifying that the platform invoke metadata is correctly formatted.

Verifying that all the managed types are valid parameters of platform invoke functions.

Locating and loading the unmanaged DLL into the process.

Locating the entry point in the process.

As you can see, it performs additional checks other than if the dll exists, like locating the entry points (e.g if SomeMethod() and SomeMethod2() actually exist in the process like in the following code).

using System.Runtime.InteropServices;

public class MY_PINVOKES
{
    [DllImport("some.dll")]
    private static void SomeMethod();

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

Then use a try/catch strategy to perform your check:

try
{
    // MY_PINVOKES class where P/Invokes are
    Marshal.PrelinkAll( typeof( MY_PINVOKES) );
}
catch
{
    // Handle error, DLL or Method may not exist
}
like image 27
Ricardo González Avatar answered Oct 07 '22 21:10

Ricardo González