How to connect to network drive in VB.net

Goal: This code provides 2 functions; 1 to connect or map a network drive, the other to disconnect the network drive. You have to pass the drive letter, unc path and optionally the username and password to the connect function.

Instructions: Open a new Windows Forms Application and add 1 button to the form. Replace all the automatically generated code in your project with the code below. All credit for this code goes to Eric Dalnas: http://www.mredkj.com/vbnet/vbnetmapdrive.html

Code:

Public Class Form1
 
    Public 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
    Public Declare Function WNetCancelConnection2 Lib "mpr" Alias "WNetCancelConnection2A" (ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer
    Public Const ForceDisconnect As Integer = 1
    Public Const RESOURCETYPE_DISK As Long = &H1
 
    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
 
    'Function to map drive/connect to drive
    Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String, ByVal strUsername As String, ByVal strPassword As String) As Boolean
 
        Dim nr As NETRESOURCE
 
        nr = New NETRESOURCE
        nr.lpRemoteName = UNCPath
        nr.lpLocalName = DriveLetter & ":"
 
        nr.dwType = RESOURCETYPE_DISK
 
        Dim result As Integer
        result = WNetAddConnection2(nr, strPassword, strUsername, 0)
 
        If result = 0 Then
            Return True
        Else
            Return False
        End If
 
    End Function
 
    'Function to disconnect from drive
    Public Function UnMapDrive(ByVal DriveLetter As String) As Boolean
        Dim rc As Integer
        rc = WNetCancelConnection2(DriveLetter & ":", 0, ForceDisconnect)
 
        If rc = 0 Then
            Return True
        Else
            Return False
        End If
 
    End Function
 
    'Connect drive X
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
         'Usage: mapdrive(driveletter, uncpath, username, password). Use "Nothing" without quotes if username or password are blank
         MapDrive("X", "\\server001", "username", "password")
    End Sub
 
End Class