dcsimg

WEBINAR:
On-Demand

Application Modernization: What Is It and How to Get Started


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!



About the Author

Hannes DuPreez

Hannes du Preez is an ex MVP for Visual Basic from 2008 to 2017. He loves technology and loves Visual Basic and C#. He loves writing articles and proving that Visual Basic is more powerful than what most believe. You are most welcome to reach him at: ojdupreez1978[at]gmail[dot]com

Related Articles

Comments

  • IT Admin

    Posted by Michael on 02/27/2018 04:34pm

    How could you utlize this same code & work in passing text thru from a textbox.text control to where the text entered would be the last folder in the UNC path string?

    Reply
  • IT

    Posted by Mike on 02/26/2018 10:18pm

    VB.net newbie here...How could you utilize this code to pass information the an end user would input into a txtbox control and click the map button?

    Reply
  • Newely Interest in Code

    Posted by Mike on 02/26/2018 09:16pm

    Vb.net beginner here. How would you utilize this code to help pass input from a text box control so that it maps based on what the user keystrokes into the box?

    Reply
  • Useful code

    Posted by Rang on 01/26/2018 06:10am

    Hi Hannes DuPreez, I appreciate your good work. Actually the code is working fine to connect the drives, but when i dry to disconnect it gives error message. Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'Application!WpfApp1.Form1::WNetCancelConnection' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'

    Reply
  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date