C# Class to establish a network connection with credentials

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
using System;
using System.Runtime.InteropServices;
 
using BOOL = System.Int32;
 
namespace NetworkConnection
{
    public class NetworkShare
    {
        #region Member Variables
        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2A(ref NetResource refNetResource, string inPassword, string inUsername, int inFlags);
        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2A(string inServer, int inFlags, int inForce);
 
        private String _Server;
        private String _Share;
        private String _DriveLetter = null;
        private String _Username = null;
        private String _Password = null;
        private int _Flags = 0;
        private NetResource _NetResource = new NetResource();
        BOOL _AllowDisconnectWhenInUse = 0; // 0 = False; Any other value is True;
        #endregion
 
        #region Constructors
        /// <summary>
        /// The default constructor
        /// </summary>
        public NetworkShare()
        {
        }
 
        /// <summary>
        /// This constructor takes a server and a share.
        /// </summary>
        public NetworkShare(String inServer, String inShare)
        {
            _Server = inServer;
            _Share = inShare;
        }
 
        /// <summary>
        /// This constructor takes a server and a share and a local drive letter.
        /// </summary>
        public NetworkShare(String inServer, String inShare, String inDriveLetter)
        {
            _Server = inServer;
            _Share = inShare;
            DriveLetter = inDriveLetter;
        }
 
        /// <summary>
        /// This constructor takes a server, share, username, and password.
        /// </summary>
        public NetworkShare(String inServer, String inShare, String inUsername, String inPassword)
        {
            _Server = inServer;
            _Share = inShare;
            _Username = inUsername;
            _Password = inPassword;
        }
 
        /// <summary>
        /// This constructor takes a server, share, drive letter, username, and password.
        /// </summary>
        public NetworkShare(String inServer, String inShare, String inDriveLetter, String inUsername, String inPassword)
        {
            _Server = inServer;
            _Share = inShare;
            _DriveLetter = inDriveLetter;
            _Username = inUsername;
            _Password = inPassword;
        }
        #endregion
 
        #region Properties
        public String Server
        {
            get { return _Server; }
            set { _Server = value; }
        }
 
        public String Share
        {
            get { return _Share; }
            set { _Share = value; }
        }
 
        public String FullPath
        {
            get { return string.Format(@"\\{0}\{1}", _Server, _Share); }
        }
 
        public String DriveLetter
        {
            get { return _DriveLetter; }
            set { SetDriveLetter(value); }
        }
 
        public String Username
        {
            get { return String.IsNullOrEmpty(_Username) ? null : _Username  ; }
            set { _Username = value; }
        }
 
        public String Password
        {
            get { return String.IsNullOrEmpty(_Password) ? null : _Username; }
            set { _Password = value; }
        }
 
        public int Flags
        {
            get { return _Flags; }
            set { _Flags = value; }
        }
 
        public NetResource Resource
        {
            get { return _NetResource; }
            set { _NetResource = value; }
        }
 
        public bool AllowDisconnectWhenInUse
        {
            get { return Convert.ToBoolean(_AllowDisconnectWhenInUse); }
            set { _AllowDisconnectWhenInUse = Convert.ToInt32(value); }
        }
 
        #endregion
 
        #region Functions
        /// <summary>
        /// Establishes a connection to the share.
        ///
        /// Throws:
        ///
        ///
        /// </summary>
        public int Connect()
        {
            _NetResource.Scope = (int)Scope.RESOURCE_GLOBALNET;
            _NetResource.Type = (int)Type.RESOURCETYPE_DISK;
            _NetResource.DisplayType = (int)DisplayType.RESOURCEDISPLAYTYPE_SHARE;
            _NetResource.Usage = (int)Usage.RESOURCEUSAGE_CONNECTABLE;
            _NetResource.RemoteName = FullPath;
            _NetResource.LocalName = DriveLetter;
 
            return WNetAddConnection2A(ref _NetResource, _Password, _Username, _Flags);
        }
 
        /// <summary>
        /// Disconnects from the share.
        /// </summary>
        public int Disconnect()
        {
            int retVal = 0;
            if (null != _DriveLetter)
            {
                retVal = WNetCancelConnection2A(_DriveLetter, _Flags, _AllowDisconnectWhenInUse);
                retVal = WNetCancelConnection2A(FullPath, _Flags, _AllowDisconnectWhenInUse);
            }
            else
            {
                retVal = WNetCancelConnection2A(FullPath, _Flags, _AllowDisconnectWhenInUse);
            }
            return retVal;
        }
 
        private void SetDriveLetter(String inString)
        {
            if (inString.Length == 1)
            {
                if (char.IsLetter(inString.ToCharArray()[0]))
                {
                    _DriveLetter = inString + ":";
                }
                else
                {
                    // The character is not a drive letter
                    _DriveLetter = null;
                }
            }
            else if (inString.Length == 2)
            {
                char[] drive = inString.ToCharArray();
                if (char.IsLetter(drive[0]) && drive[1] == ':')
                {
                    _DriveLetter = inString;
                }
                else
                {
                    // The character is not a drive letter
                    _DriveLetter = null;
                }
            }
            else
            {
                // If we get here the value passed in is not valid
                // so make it null.
                _DriveLetter = null;
            }
        }
        #endregion
 
        #region NetResource Struct
        [StructLayout(LayoutKind.Sequential)]
        public struct NetResource
        {
            public uint Scope;
            public uint Type;
            public uint DisplayType;
            public uint Usage;
            public string LocalName;
            public string RemoteName;
            public string Comment;
            public string Provider;
        }
        #endregion
 
        #region Enums
        public enum Scope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_GLOBALNET,
            RESOURCE_REMEMBERED,
            RESOURCE_RECENT,
            RESOURCE_CONTEXT
        }
 
        public enum Type : uint
        {
            RESOURCETYPE_ANY,
            RESOURCETYPE_DISK,
            RESOURCETYPE_PRINT,
            RESOURCETYPE_RESERVED = 8,
            RESOURCETYPE_UNKNOWN = 4294967295
        }
 
        public enum DisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }
 
        public enum Usage : uint
        {
            RESOURCEUSAGE_CONNECTABLE = 1,
            RESOURCEUSAGE_CONTAINER = 2,
            RESOURCEUSAGE_NOLOCALDEVICE = 4,
            RESOURCEUSAGE_SIBLING = 8,
            RESOURCEUSAGE_ATTACHED = 16,
            RESOURCEUSAGE_ALL = 31,
            RESOURCEUSAGE_RESERVED = 2147483648
        }
 
        public enum ConnectionFlags : uint
        {
            CONNECT_UPDATE_PROFILE = 1,
            CONNECT_UPDATE_RECENT = 2,
            CONNECT_TEMPORARY = 4,
            CONNECT_INTERACTIVE = 8,
            CONNECT_PROMPT = 16,
            CONNECT_NEED_DRIVE = 32,
            CONNECT_REFCOUNT = 64,
            CONNECT_REDIRECT = 128,
            CONNECT_LOCALDRIVE = 256,
            CONNECT_CURRENT_MEDIA = 512,
            CONNECT_DEFERRED = 1024,
            CONNECT_COMMANDLINE = 2048,
            CONNECT_CMD_SAVECRED = 4096,
            CONNECT_CRED_RESET = 8192,
            CONNECT_RESERVED = 4278190080
        }
        #endregion
    }
}

Hopefully I will get time to explain what is going on here.

One Comment

  1. Derek says:

    Thanks, this is great stuff! Thanks for showing how to do this.

Leave a Reply

How to post code in comments?