WNetAddConnection2 returns Error 1200 - The local name is valid

I am trying to connect a share (say \ server \) to my local device 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;
    }

Upon call

Connect(@"\\server\folder", "X:", true);

the function simply returns false - the error says 1200 (BAD_DEVICE). NetResource looks like this:

lpRemoteName = "\\\\server\\folder"; 
lpProvider = null;
lpLocalName = "X:";
lpComment = null;
dwUsage = Connectable; 
dwType = Any; 
dwScope = GlobalNet; 
dwDisplayType = Share;

I already checked some fragments (PInvoke), I do not see any difference. Maybe you can solve this mystery ...

EDIT1

Variables when trying to map a drive

+6
source share
2 answers
[StructLayout(LayoutKind.Sequential)]

, CharSet. CharSet.Ansi - , , , 1998 . , , 8- , Unicode- . .

[MarshalAs]. . Fix:

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

, , .

,

[MarshalAs(UnmanagedType.LPWStr)] 

NetResource. , , ...

+1

All Articles