There are times when working with network drives it becomes necessary in an application to create or remove a network share. We don’t want an unhanded exception if the path is not mapped correctly or if it does not exist. (often users will screw this up after it has been correctly imaged on their machine). I actually ran into this at one point at GE Healthcare. Here is a very watered down sample of this (basically for security reasons). One caveat: The windows script host must be enabled for this to work.
' Add a COM reference to Windows Script Host Object Model. Imports IWshRuntimeLibrary Imports System.Runtime.InteropServices Public Class NetworkDriveMapper Public Shared Sub MapDrive(ByVal driveLetter As String, _ ByVal networkPath As String, ByVal isPersistent As Boolean) ' Create a new shell object. Dim networkShell As New WshNetwork() Try ' Disconnect the drive first, forcing a permanent change. DisconnectDrive(driveLetter, True, True) ' Map the drive to the path. networkShell.MapNetworkDrive(driveLetter, networkPath, Convert.ToBoolean(isPersistent)) Finally If Not networkShell Is Nothing Then Marshal.ReleaseComObject(networkShell) networkShell = Nothing End If End Try End Sub Public Shared Sub DisconnectDrive(ByVal driveLetter As String, _ ByVal willForce As Boolean, ByVal isPersistent As Boolean) ' Create a new shell object. Dim networkShell As New WshNetwork() If IO.Directory.Exists(driveLetter) Then Try networkShell.RemoveNetworkDrive(driveLetter, Convert.ToBoolean(willForce), _ Convert.ToBoolean(isPersistent)) Finally If Not networkShell Is Nothing Then Marshal.ReleaseComObject(networkShell) networkShell = Nothing End If End Try End If End Sub End Class
#1 by Rick Agustin on March 13, 2012 - 3:13 pm
Exactly what I needed — no fuss code. Thanks, Kelly!