WNetAddConnection2返回错误1200 - 本地名称有效

时间:2017-07-27 05:58:08

标签: c# network-programming share wnet

我尝试将共享(让我们说\ server \文件夹)连接到我的本地设备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

Variables when trying to map the drive

2 个答案:

答案 0 :(得分:3)

[StructLayout(LayoutKind.Sequential)]

这是问题开始的地方,该属性未指定CharSet属性。默认值是CharSet.Ansi,这是一个令人眼花缭乱的选择,需要在时间机器中进行操作才能理解,然后再回到1998年。因此代码将带有字符串的结构传递给8位字符转换为函数显式使用函数的Unicode风格。实施不可避免地会看到垃圾。

您可以使用[MarshalAs]强制每个字符串成员的编组。但是使字符类型匹配更简单合理。修正:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]

答案 1 :(得分:1)

我终于做到了。

我通过添加

解决了这个问题
[MarshalAs(UnmanagedType.LPWStr)] 

NetResource类中每个字符串字段的属性。不幸的是,我不知道为什么这会解决这个问题......