C4p*_*1nZ 6 c# share network-programming wnet
我正在尝试将共享(假设为\ server\folder)连接到我的本地设备X:
[DllImport("Mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int WNetAddConnection2(
[In] NetResource lpNetResource,
string lpPassword,
string lpUsername,
int flags
);
public static bool Connect(string remoteName, string localName, bool persistent) {
if (!IsLocalPathValid(localName)) return false;
var r = new NetResource
{
dwScope = ResourceScope.RESOURCE_GLOBALNET,
dwType = ResourceType.RESOURCETYPE_ANY,
dwDisplayType = ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE,
dwUsage = ResourceUsage.RESOURCEUSAGE_CONNECTABLE,
lpRemoteName = remoteName,
lpLocalName = localName
};
return WNetAddConnection2(r, null, null, persistent ? 1 : 0) == 0;
}
[StructLayout(LayoutKind.Sequential)]
public class NetResource {
public ResourceScope dwScope;
public ResourceType dwType;
public ResourceDisplayType dwDisplayType;
public ResourceUsage dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
public string lpProvider;
}
Run Code Online (Sandbox Code Playgroud)
打电话的时候
Connect(@"\\server\folder", "X:", true);
Run Code Online (Sandbox Code Playgroud)
函数只返回false - 错误说1200(BAD_DEVICE).NetResource看起来像这样:
lpRemoteName = "\\\\server\\folder";
lpProvider = null;
lpLocalName = "X:";
lpComment = null;
dwUsage = Connectable;
dwType = Any;
dwScope = GlobalNet;
dwDisplayType = Share;
Run Code Online (Sandbox Code Playgroud)
我已经检查了几个片段(PInvoke)把我看不出任何区别.也许你可以解开这个谜......
EDIT1
[StructLayout(LayoutKind.Sequential)]
Run Code Online (Sandbox Code Playgroud)
这就是问题开始的地方,属性没有指定CharSet属性。默认值是 CharSet.Ansi,这是一个令人困惑的选择,需要乘坐时光机才能理解,带您回到 1998 年。因此,代码将一个带有字符串的结构体传递给一个函数,该字符串被转换为 8 位字符明确使用该函数的 Unicode 风格。实施过程中不可避免地会出现垃圾。
您可以使用 [MarshalAs] 强制对每个单独的字符串成员进行封送。但使字符类型匹配更简单、更符合逻辑。使固定:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
Run Code Online (Sandbox Code Playgroud)