Mapping/unmapping drives failing

922 views Asked by At

I need to first map and then later unmap 2x drives using VB.NET.

When mapping the drives, I also need to pass a username and password (as not all users have admin access).

However, not only is the below not working (failing to map, so in turn failing to unmap), but I notice that I only have the option to pass a password when mapping a drive, not a username.

Can anyone help me in fixing these problems? Thanks.

Private Declare Function WNetAddConnection Lib "mpr.dll" Alias "WNetAddConnectionA" (ByVal lpszNetPath As String,
                                                                                     ByVal lpszPassword As String,
                                                                                     ByVal lpszLocalName As String) As Long
Private Declare Function WNetCancelConnection Lib "mpr.dll" Alias "WNetCancelConnectionA" (ByVal lpszName As String,
                                                                                           ByVal bForce As Long) As Long

Public Function MapDrive(ByVal UNCPath As String, ByVal Password As String, ByVal DriveLetter As String) As Boolean

    Dim MappedResult As Long = WNetAddConnection(UNCPath, Password, DriveLetter)

    Return IIf(MappedResult = 0, True, False)

End Function

Public Function UnmapDrive(ByVal DriveLetter As String) As Boolean

    Dim UnmappedResult As Long = WNetCancelConnection(DriveLetter, 0)

    Return IIf(UnmappedResult = 0, True, False)

End Function
1

There are 1 answers

1
Chris Tybur On BEST ANSWER

You should switch to using the WNetAddConnection2/WNetCancelConnection2 functions. The former allows you to specify a username in the call. Here are the PInvoke signatures I've used successfully in the past:

Private Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" _
    (ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, _
     ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer

Private Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias "WNetCancelConnection2A" _
    (ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer

Private Declare Function WNetGetLastError Lib "mpr.dll" Alias "WNetGetLastErrorA" _
    (ByRef nError As Integer, ByRef lpErrorBuf As String, ByVal nErrorBufSize As Integer, _
     ByRef lpNamebuf As String, ByVal nNameBufSize As Integer) As Integer

<StructLayout(LayoutKind.Sequential)> _
    Public Structure NETRESOURCE
    Public dwScope As Integer
    Public dwType As Integer
    Public dwDisplayType As Integer
    Public dwUsage As Integer
    Public lpLocalName As String
    Public lpRemoteName As String
    Public lpComment As String
    Public lpProvider As String
End Structure

Private Const ForceDisconnect As Integer = 1
Private Const RESOURCETYPE_DISK As Long = &H1

GetLastError is useful for figuring out why the mapping failed (bad password, etc).