Mapping and Un-mapping Network Drives with VB.NET

Mapped Drives

Mapped Drives are hard drives—even if the particular drive is located on a Cloud or virtual computing system, or on a network drive. Mapped drives are represented in a similar manner than ordinary drives and folders on your PC.

In the Practical section, that follows next, you will learn how to map network drives from VB as well as to un-map those drive(s). Let’s start!

Practical

Open Visual Studio and create a new Visual Basic Windows Forms project. You may name your project anything you want, as well as your objects and form; keep in mind that my names may be different than your object names. Your form will contain only two buttons: one button to map the drive and another to un-map the drive. It looks like Figure 1.

Design
Figure 1: Design

Code

Add the following code to import the InteropServices namespace that allows you to make use of the system’s Windows API functions:

Imports System.Runtime.InteropServices

Add the Windows APIs to create the mapping and to un-map the drive(s):

   <DllImportAttribute("mpr.dll", _
      EntryPoint:="WNetAddConnection2W")>
   Public Shared Function WNetAddConnection2(ByRef lpNetResource _
      As NETRESOURCE, <InAttribute(), _
      MarshalAsAttribute(UnmanagedType.LPWStr)> ByVal _
      lpPassword As String, <InAttribute(), _
      MarshalAsAttribute(UnmanagedType.LPWStr)> ByVal _
      lpUserName As String, ByVal dwFlags As UInteger) As UInteger
   End Function

   <DllImportAttribute("mpr.dll", _
      EntryPoint:="WNetCancelConnectionW")>
   Public Shared Function WNetCancelConnection(<InAttribute(), _
      MarshalAsAttribute(UnmanagedType.LPWStr)> ByVal _
      lpName As String, ByVal dwFlags As UInteger, _
      <MarshalAsAttribute(UnmanagedType.Bool)> ByVal _
      fForce As Boolean) As UInteger
   End Function

WNetAddConnection2 creates a connection to a network resource. WNetCancelConnection cancels an existing network connection.

Add the necessary constants:

   Public Const NO_ERROR As UInteger = 0
   Public Const RESOURCETYPE_DISK As UInteger = 1
   Public Const CONNECT_UPDATE_PROFILE As UInteger = 1

No_ERROR means that the specified operation succeeded. RESOURCETYPE_DISK represents a disk.

Add the NETRESOURCE Structure that will assist in setting up the drive to be mapped or un-mapped properly:

   <StructLayoutAttribute(LayoutKind.Sequential)>
      Public Structure NETRESOURCE

      Public dwScope As UInteger
      Public dwType As UInteger
      Public dwDisplayType As UInteger
      Public dwUsage As UInteger

      <MarshalAsAttribute(UnmanagedType.LPWStr)>
      Public lpLocalName As String

      <MarshalAsAttribute(UnmanagedType.LPWStr)>
      Public lpRemoteName As String

      <MarshalAsAttribute(UnmanagedType.LPWStr)>
      Public lpComment As String

      <MarshalAsAttribute(UnmanagedType.LPWStr)>
      Public lpProvider As String

   End Structure

Add the Map Sub procedure:

   Public Shared Sub Map(ByVal strPath As String, _
         ByVal strDrive As Char, ByVal blnPersist As Boolean, _
         Optional ByVal strUser As String = Nothing, _
         Optional ByVal strPassword As String = Nothing)

      Dim nrDrive As New NETRESOURCE

      With nrDrive

         .dwType = RESOURCETYPE_DISK
         .lpLocalName = strDrive & ":"
         .lpRemoteName = strPath

      End With

      Dim uiSet As UInteger = 0

      If blnPersist Then

         uiSet = &H1

      End If

      Dim uiRes As UInteger = WNetAddConnection2(nrDrive, _
         strPassword, strUser, uiSet)

      If Not uiRes = NO_ERROR Then

         Throw New System.ComponentModel.Win32Exception _
            (CInt(uiRes))

      End If

   End Sub

And call it from your ‘Map’ button:

   Private Sub Button1_Click(sender As Object, e As EventArgs) _
         Handles Button1.Click

      Try

         Map("\\Server\Share", "T"c, False)

      Catch ex As Exception

         MessageBox.Show(ex.Message)

      End Try

   End Sub

From button1, you simply supplied the Path as well as the desired Drive letter. You could have submitted your Username and password as well, depending on your computer’s security restrictions.

Add the Unmap Sub procedure as well as its call:

   Public Shared Sub Unmap(ByVal cDrive As Char)

      Dim uiRes As UInteger = WNetCancelConnection(cDrive & ":", _
         CONNECT_UPDATE_PROFILE, True)

      If Not uiRes = NO_ERROR Then

         Throw New System.ComponentModel.Win32Exception _
            (CInt(uiRes))

      End If

   End Sub

   Private Sub Button2_Click(sender As Object, e As EventArgs) _
         Handles Button2.Click

      Unmap("T"c)

   End Sub

The Unmap procedure removes the map that you created previously.

This project’s code can be found and downloaded on GitHub.

Conclusion

This article has shown you how easy it is to map network drives as well as remove the links. Hopefully, you can make good use of it. Until next time, thanks for reading!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read