调用 dll 出现 The system cannot find the file specified 错误

C# 中, 调用 dll 出现 The system cannot find the file specified 错误

最近在测试,使用的是 Hebrew 希伯来语的 Windows 10 系统,测试 C# 调用 newdev.dll 中的 UpdateDriverForPlugAndPlayDevices() 去安装驱动,该方法的声明如下:

[DllImport("newdev.dll", SetLastError = true)]
public static extern bool UpdateDriverForPlugAndPlayDevices(IntPtr hwndParent, string HardwareId, string FullInfPath, UpdateDriverInstallFlag install, out Boolean bRebootRequired);

在英文版的系统中测试正常,但是在 Hebrew 语的系统就报错,提示 “The system cannot find the file specified”,系统无法找到指定文件

但是传递的驱动文件是确切存在的,不过因为存放驱动的目录在用户目录下,我就思考是否因为路径的问题,因为路径包含 Hebrew 语的字符,导致 UpdateDriverForPlugAndPlayDevices() 无法识别文件路径,所以才提示无法找到指定文件

查找资料,发现 C# 在调用 dll 的方法时,确实可以指定字符集,见:Specifying a Character Set

然后我把 UpdateDriverForPlugAndPlayDevices() 方法的声明改为:

[DllImport("newdev.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool UpdateDriverForPlugAndPlayDevices(IntPtr hwndParent, string HardwareId, string FullInfPath, UpdateDriverInstallFlag install, out Boolean bRebootRequired);

在 DllImport 中添加了 CharSet = CharSet.Auto,测试后问题果然解决

推荐阅读:

C# 判断程序是否以管理员身份运行