![](/img/trans.png)
[英]WNetAddConnection2 and error 1219 - Automatically disconnect?
[英]WNetAddConnection2 returns Error 1200 - Local name is valid
我正在尝试将共享(假设为\\ 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;
}
打电话的时候
Connect(@"\\server\folder", "X:", true);
函数只返回false - 错误说1200(BAD_DEVICE)。 NetResource看起来像这样:
lpRemoteName = "\\\\server\\folder";
lpProvider = null;
lpLocalName = "X:";
lpComment = null;
dwUsage = Connectable;
dwType = Any;
dwScope = GlobalNet;
dwDisplayType = Share;
我已经检查了几个片段(PInvoke)把我看不出任何区别。 也许你可以解开这个谜......
EDIT1
[StructLayout(LayoutKind.Sequential)]
这是问题开始的地方,该属性未指定CharSet
属性。 默认值是CharSet.Ansi,这是一个令人眼花缭乱的选择,需要在时间机器中进行操作才能理解,然后再回到1998年。因此代码将带有字符串的结构传递给8位字符转换为函数显式使用函数的Unicode风格。 实施不可避免地会看到垃圾。
您可以使用[MarshalAs]强制每个字符串成员的编组。 但是使字符类型匹配更简单合理。 固定:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
我终于做到了。
我通过添加解决了这个问题
[MarshalAs(UnmanagedType.LPWStr)]
NetResource类中每个字符串字段的属性。 不幸的是我不知道为什么这个问题解决了......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.