Search code examples
vb.netmapped-drivepersistent-connection

vb.net how to check if a network drive is mapped persistently


I use the following code to layout network drives on a system. I want to add a third column for persistence but in vb.net I do not know how to check if a drive has a persistent map or not. Any suggestions?

For Each drive_info As DriveInfo In DriveInfo.GetDrives()
        If drive_info.DriveType().ToString = "Network" Then
            With maps.Items.Add(drive_info.Name)
                .SubItems.Add(drive_info.DriveType().ToString)
            End With
        End If
    Next drive_info

Solution

  • You could have always done it in WMI without any (well okay fewer) nasty cludges.

    e.g.

    Imports System
    Imports System.Management
    
    Public Module modmain
       Sub Main()
        Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_NetworkConnection WHERE LocalName = 'Z:'")
        Dim obj As ManagementObject
        For Each obj In searcher.Get
            Console.WriteLine("{0} {1}", obj.Item("LocalName").ToString, obj.Item("Persistent"))
        Next
       End Sub
    End Module
    

    Obviously you need to add a reference to System.Management.dll and change Z: to the drive you are checking, or you could probably replace all your code with just that snippet as removing the WHERE clause will return all mapped drives.