VB.NET – Delete existing network drive

May 30, 2010 — Leave a comment

As I demonstrated how to map a network drive in my last post, it seems like it might be a good idea to explain how to delete an existing mapped drive as well. Again we have to rely on Windows APIs to do this… but its a pretty simple one this time (for once).

Here are the API definitions, with my comments:

Public Const CONNECT_UPDATE_PROFILE As UInteger = 1
Public Const NO_ERROR As UInteger= 0”’ <summary>
”’ Deletes a connection to a network resource
”’ </summary>
”’ <param name=”lpName”>The name of the connection to delete (e.g drive letter)</param>
”’ <param name=”dwFlags”>If this is a persistent connection set to CONNECT_UPDATE_PROFILE to prevent from being mapped again at next logon</param>
”’ <param name=”fForce”>Delete connection even if files from this resource are still open</param>
<DllImportAttribute(“mpr.dll”, EntryPoint:=“WNetCancelConnection2W”)> _
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

and here is my .NET method that wraps that API:

”’ <summary>
”’ Deletes an existing mapped network drive
”’ </summary>
”’ <param name=”DriveLetter”>The drive letter to delete, must be a network drive</param>
”’ <param name=”Force”>Force the drive to be deleted even if files are still open on this drive</param>
Public Shared Sub RemoveNetworkDrive(ByVal DriveLetter As Char, ByVal Force As Boolean)
Dim Result As UInteger = WNetCancelConnection(DriveLetter & “:”, CONNECT_UPDATE_PROFILE, Force)
If Not Result = NO_ERROR Then
Throw New System.ComponentModel.Win32Exception(CInt(Result))
End If
End Sub

So when you want to delete a mapped drive you just do this:

‘Deletes the F drive (only if it is a network drive)
RemoveNetworkDrive(“F”c, True)
‘The second argument specifies that we want to force
‘it to be deleted even if there are files open from this drive

Job done 🙂

No Comments

Be the first to start the conversation!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s