You are currently offline, waiting for your internet to reconnect

How To Use the WNetUseConnection API to Map a Drive in Visual Basic

This article was previously published under Q256847
This article demonstrates how to use the WNetUseConnection API function to map a system-supplied drive letter to a network share. In addition, the WNetCancelConnection2 API function is demonstrated to show how to disconnect a mapped drive.
At times, it is necessary to map a drive letter to a network share. There are several API functions that can be used to accomplish this, such as WNetAddConnection, WNetAddConnection2, WNetAddConnection3, and WNetUseConnection. The primary difference is that with the WNetUseConnection function, you do not need to specify the drive letter to be used, while it is required with the other API functions.

Steps to Create Sample

  1. Create a new Standard EXE project in Visual Basic. Form1 is created by default.
  2. Add three TextBox controls to Form1 and name them txtUNC, txtUser, and txtPWD.
  3. Set the PasswordChar property of txtPWD to an asterisk (*).
  4. Add two CommandButtons to Form1 and set their Captions to CONNECT and DISCONNECT.
  5. Paste the following code into the code window of Form1:
    Option Explicit' CONSTANTSPrivate Const NO_ERROR = 0Private Const CONNECT_LOCALDRIVE = 256Private Const CONNECT_REDIRECT = 128Private Const RESOURCE_GLOBALNET = &H2Private Const RESOURCETYPE_DISK = &H1Private Const RESOURCEDISPLAYTYPE_SHARE = &H3Private Const RESOURCEUSAGE_CONNECTABLE = &H1Private Const CONNECT_UPDATE_PROFILE = 1' LOCAL VARIABLESPrivate MappedDrive As String' CUSTOM TYPESPrivate Type NETRESOURCE    dwScope As Long    dwType As Long    dwDisplayType As Long    dwUsage As Long    lpLocalName As String    lpRemoteName As String    lpComment As String    lpProvider As StringEnd Type' API DECLARATIONSPrivate Declare Function WNetUseConnection Lib "mpr.dll" _   Alias "WNetUseConnectionA" ( _   ByVal hwndOwner As Long, _   ByRef lpNetResource As NETRESOURCE, _   ByVal lpUsername As String, _   ByVal lpPassword As String, _   ByVal dwFlags As Long, _   ByVal lpAccessName As Any, _   ByRef lpBufferSize As Long, _   ByRef lpResult As Long) _   As LongPrivate Declare Function WNetCancelConnection2 Lib "mpr.dll" _   Alias "WNetCancelConnection2A" ( _   ByVal lpName As String, _   ByVal dwFlags As Long, _   ByVal fForce As Long) _   As LongPrivate Sub Command1_Click()   Dim NetR As NETRESOURCE    ' NetResouce structure   Dim ErrInfo As Long        ' Return value from API   Dim buffer As String       ' Drive letter assigned to resource   Dim bufferlen As Long      ' Size of the buffer   Dim success As Long        ' Additional info about API call      ' Initialize the NetResouce structure   NetR.dwScope = RESOURCE_GLOBALNET   NetR.dwType = RESOURCETYPE_DISK   NetR.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE   NetR.dwUsage = RESOURCEUSAGE_CONNECTABLE   NetR.lpLocalName = vbNullString   NetR.lpRemoteName = txtUNC.Text   ' Initialize the return buffer and buffer size   buffer = Space(32)   bufferlen = Len(buffer)   ' Call API to map the drive   ErrInfo = WNetUseConnection(Me.hWnd, NetR, txtPWD.Text, txtUser.Text, _      CONNECT_REDIRECT, buffer, bufferlen, success)   ' Check if call to API failed. According to the MSDN help, there   ' are some versions of the operating system that expect the userid   ' as the 3rd parameter and the password as the 4th, while other   ' versions of the operating system have them in reverse order, so   ' if first call to API fails, try reversing these two parameters.   If ErrInfo <> NO_ERROR Then      ' Call API with userid and password switched      ErrInfo = WNetUseConnection(Me.hWnd, NetR, txtUser.Text, _         txtPWD.Text, CONNECT_REDIRECT, buffer, bufferlen, success)   End If   ' Check for success   If (ErrInfo = NO_ERROR) And (success = CONNECT_LOCALDRIVE) Then      ' Store the mapped drive letter for later usage      MappedDrive = Left$(buffer, InStr(1, buffer, ":"))      ' Display the mapped drive letter      MsgBox "Connect Succeeded to " & MappedDrive   Else      MsgBox "ERROR: " & Str(ErrInfo) & " - Connect Failed!"   End IfEnd SubPrivate Sub Command2_Click()   Dim ErrInfo As Long     ' Return value from API   ' Call API to disconnect the drive   ErrInfo = WNetCancelConnection2(MappedDrive, _      CONNECT_UPDATE_PROFILE, False)   ' Check for success   If ErrInfo = NO_ERROR Then      MsgBox "Disconnect of '" & MappedDrive & "' Succeeded"            ' Clear the mapped drive letter      MappedDrive = ""   Else      MsgBox "ERROR: " & Str(ErrInfo) & " - Disconnect Failed!"   End IfEnd Sub					
  6. Save and run the sample.
  7. In the first TextBox, type the UNC path to the share you wish to map to a drive letter (such as, \\ServerName\ShareName).
  8. In the second TextBox, type your network logon name.
  9. In the third TextBox, type your password.
  10. Click the CONNECT button.

    RESULT: Provided you have typed a valid user id, password, network share, and have the appropriate network permissions, you should receive a message indicating that the share was connected and the mapped drive letter is given. You can verify the map by opening the Windows Explorer.
  11. Click the DISCONNECT button.

    RESULT: The mapped drive is disconnected. Again, this can be verified with the Windows Explorer.
For additional information on creating network connections with API calls from Visual Basic, click the article number below to view the article in the Microsoft Knowledge Base:
173011 How To Add and Remove Network Connections

Article ID: 256847 - Last Review: 08/30/2004 22:05:00 - Revision: 2.2

  • Microsoft Visual Basic 6.0 Learning Edition
  • Microsoft Visual Basic 6.0 Professional Edition
  • Microsoft Visual Basic 6.0 Enterprise Edition
  • Microsoft Visual Basic 5.0 Control Creation Edition
  • Microsoft Visual Basic 5.0 Learning Edition
  • Microsoft Visual Basic 5.0 Professional Edition
  • Microsoft Visual Basic 5.0 Enterprise Edition
  • Microsoft Visual Basic 4.0 Standard Edition
  • Microsoft Visual Basic 4.0 Professional Edition
  • Microsoft Visual Basic 4.0 32-Bit Enterprise Edition
  • kbhowto kbapi kbwnet KB256847