File size: 2,544 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#nullable enable

using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class Windows
    {
        internal const int CONNECT_NOPERSIST = 0x00000000;
        internal const int CONNECT_UPDATE_PROFILE = 0x00000001;
        internal const int RESOURCE_GLOBALNET = 0x00000002;
        internal const int RESOURCETYPE_ANY = 0x00000000;
        internal const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
        internal const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;

        [StructLayout(LayoutKind.Sequential)]
        internal unsafe struct NETRESOURCEW
        {
            public int Scope;
            public int Type;
            public int DisplayType;
            public int Usage;
            public char* LocalName;
            public char* RemoteName;
            public char* Comment;
            public char* Provider;
        }

        [LibraryImport("mpr.dll", EntryPoint = "WNetAddConnection2W", StringMarshalling = StringMarshalling.Utf16)]
        internal static partial int WNetAddConnection2(ref NETRESOURCEW netResource, byte[] password, string userName, int flags);

        internal static unsafe int WNetAddConnection2(string localName, string remoteName, byte[] password, string userName, int connectType)
        {
            if (s_WNetApiNotAvailable)
            {
                return ERROR_NOT_SUPPORTED;
            }

            int errorCode = ERROR_NO_NETWORK;

            fixed (char* pinnedLocalName = localName)
            fixed (char* pinnedRemoteName = remoteName)
            {
                NETRESOURCEW resource = new NETRESOURCEW()
                {
                    Comment = null,
                    DisplayType = RESOURCEDISPLAYTYPE_GENERIC,
                    LocalName = pinnedLocalName,
                    Provider = null,
                    RemoteName = pinnedRemoteName,
                    Scope = RESOURCE_GLOBALNET,
                    Type = RESOURCETYPE_ANY,
                    Usage = RESOURCEUSAGE_CONNECTABLE
                };

                try
                {
                    errorCode = WNetAddConnection2(ref resource, password, userName, connectType);
                }
                catch (System.DllNotFoundException)
                {
                    s_WNetApiNotAvailable = true;
                    return ERROR_NOT_SUPPORTED;
                }
            }

            return errorCode;
        }
    }
}