Free Information Technology Magazines and eBooks

Tuesday, May 19, 2009

How to map shared network folder using VB.NET

How to map shared network folder using VB.NETMicrosoft .NET do not have available namespace or command to directly map shared network folder. To map a shared folder you still need to access the WinAPI or use the NET USE command. Today we will explore the usage of WNetAddConnection2A and how we can use it to map any network shared folder. This article also contains a sample project that you can download and study.



To start, you need to include the following namespace in your VB.NET project:

Imports System.Runtime.InteropServices


Then inside your form class, delare the WNetAddConnection2 and WNetCancelConnection2 WINAPIs.

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


Also after the declaration of WINAPIs, create a public structure like the one below:

<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


And then defined some constants that will be used later.


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


Now after we finished declaring the prerequisites, Lets code the functions to Map an UnMap shared folder.

Function to Map a shared Folder

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

Dim nr As NETRESOURCE
Dim strUsername As String
Dim strPassword As String

nr = New NETRESOURCE
nr.lpRemoteName = UNCPath
nr.lpLocalName = DriveLetter & ":"

strUsername = Nothing
strPassword = Nothing
If txtUsername.Text.Length > 0 Then
strUsername = txtUsername.Text
End If
If txtPassword.Text.Length > 0 Then
strPassword = txtPassword.Text
End If

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 Un-Map shared folder

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


Map shared network folder

Its finished, you application should be able to map shared network folder. To get the Visual Studio 2005 sample project I created, download it here.

For more VB.NET tips and tricks, subscribe now


0 comments: