[2005] Map Network Drives
I need to map a network drive via code and found that .Net cannot do this directly so I tied to use API calls. Below is a start. The problem is that none of the errors are defined. To find the one that is shown, I forced an error then stepped through the code. There has to be a better way.
VB Code:
Private Sub MapDrive(ByVal strDrive As String, ByVal strPath As String)
Dim err As Long
Dim ERROR_ALREADY_ASSIGNED As Long = 8192874795449188437
err = WNetAddConnection(strPath, "", strDrive)
Select Case (err)
Case ERROR_ALREADY_ASSIGNED
WNetCancelConnection(strDrive, CType(True, Integer))
WNetAddConnection(strPath, "", strDrive)
End Select
End Sub
I figured that the mapped drive was simply a key in the registry and I was correct (sort of). I can do this and create a key in the registry.
VB Code:
Private Sub MapDrive(ByVal strDrive As String, ByVal strPath As String)
Dim regKey As RegistryKey = _
Registry.CurrentUser.CreateSubKey("Network\" & strDrive)
If Not (regKey Is Nothing) Then
regKey.SetValue("ConnectionType", 1)
regKey.SetValue("DeferFlags", 4)
regKey.SetValue("ProviderName", "Microsoft Windows Network")
regKey.SetValue("ProviderType", 131072)
regKey.SetValue("RemotePath", strPath)
regKey.SetValue("UserName", 0)
End If
End Sub
This makes a correct entry into the registry and the newly mapped drive appears in both the "Map Network Drive" and "Disconnect Network Drive" dialogs but it does not appear in "My Computer". I like this method because it modifies the registry even if the drive already exists. Can someone shed some light on what I'm missing with the registry approach?
Re: [2005] Map Network Drives
I just found that if I create the registry key then restart my PC the drive is properly mapped. There must be a service that gets started/restarted when a drive is mapped using the API.