检查系统中是否存在DLL

fea*_*l87 8 c# windows dll pinvoke winapi

快速的问题.我想知道我的应用程序正在执行的系统中是否存在DLL.

这可能在C#中吗?(以某种方式适用于所有Windows操作系统?)

对于DLL我的意思是一个非.NET经典DLL(一个Win32 DLL)

(基本上我想做一个检查,因为我使用的DLL可能会或可能不会出现在用户系统上,但我不希望应用程序在没有警告时崩溃:P)

SLa*_*aks 15

调用LoadLibraryAPI函数:

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

static bool CheckLibrary(string fileName) {
    return LoadLibrary(fileName) == IntPtr.Zero;
}
Run Code Online (Sandbox Code Playgroud)

  • 恕我直言*需要FreeLibrary* - 否则你泄漏了对库的引用.这可能现在无关紧要,但在将来,有人会认为CheckLibrary没有副作用,它会烧伤你. (5认同)
  • 这不只是检查库,它加载它并保持它加载.你必须手动FreeLibrary. (2认同)

Dr *_*nke 6

在 .NET 中使用平台调用时,可以使用以下Marshal.PrelinkAll(Type)方法:

设置任务提供早期初始化,并在调用目标方法时自动执行。首次任务包括以下内容:

验证平台调用元数据的格式是否正确。

验证所有托管类型是否都是平台调用函数的有效参数。

定位非托管 DLL 并将其加载到进程中。

找到流程中的入口点。

正如您所看到的,除了 dll 是否存在之外,它还会执行其他检查,例如定位入口点(例如,进程中SomeMethod()是否SomeMethod2()实际存在,如以下代码所示)。

using System.Runtime.InteropServices;

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

    [DllImport("some.dll")]
    private static void SomeMethod2();
}
Run Code Online (Sandbox Code Playgroud)

然后使用try/catch策略来执行检查:

try
{
    // MY_PINVOKES class where P/Invokes are
    Marshal.PrelinkAll( typeof( MY_PINVOKES) );
}
catch
{
    // Handle error, DLL or Method may not exist
}
Run Code Online (Sandbox Code Playgroud)