使用C#调用WNetAddConnection2映射网络驱动器遇错误87
错误87(无效参数)的原因及修复方案
核心问题:NETRESOURCE类型定义错误
你将NETRESOURCE定义为class,但Win32 API的WNetAddConnection2函数期望接收的是值类型结构体的指针。使用class并配合ref修饰符时,传递的是引用类型的引用(即指针的指针),这和API预期的参数类型不匹配,直接导致了错误87。
修复步骤
- 将NETRESOURCE从class改为struct:Win32中的
NETRESOURCE是值类型结构体,C#中对应使用struct才能保证内存布局和API要求一致。 - 显式指定调用约定(推荐):在
DllImport中添加CallingConvention = CallingConvention.Winapi,避免默认调用约定不匹配的潜在问题。 - 显式初始化所有字段:即使部分字段默认值为0,显式设置能让代码更清晰,避免意外。
修正后的完整代码
using System; using System.ComponentModel; using System.Runtime.InteropServices; static class InternalHelpers { private const int RESOURCETYPE_DISK = 0x00000001; [DllImport("mpr.dll", CallingConvention = CallingConvention.Winapi)] private static extern int WNetAddConnection2( ref NETRESOURCE netResource, string password, string username, int flags); [StructLayout(LayoutKind.Sequential)] private struct NETRESOURCE { public int dwScope; public int dwType; public int dwDisplayType; public int dwUsage; public string lpLocalName; public string lpRemoteName; public string lpComment; public string lpProvider; } public static bool MapNetworkDrive(string driveLetter, string networkPath, string username, string password) { NETRESOURCE nr = new NETRESOURCE { dwScope = 0, dwType = RESOURCETYPE_DISK, dwDisplayType = 0, dwUsage = 0, lpLocalName = $"{driveLetter}:", lpRemoteName = networkPath, lpComment = null, lpProvider = null }; int result = WNetAddConnection2(ref nr, password, username, 0); if (result != 0) { throw new Win32Exception(result); } return true; } }
额外验证点
- 确认目标UNC路径
\\10.1.100.126\codes真实存在,且传入的Administrator账号有访问权限。 - 检查Z盘未被其他进程占用。
内容的提问来源于stack exchange,提问作者Combinu
相关产品推荐
相关产品推荐

