Search code examples
vb.netuncshared-directory

VB.NET code to Convert shared local path to UNC path


We have windows 2003 server Pc named pc2 in which local drives are shared with different names. For example local drive E is shared with name 'datapath' so that all users in network access that drive using network path '\\pc2\datapath\'. We need VB.net code to convert local path to shared UNC path i.e if we input 'E:\netuse',code must return '\\pc2\datapath\netuse'.

Is there any way to do this in VB.net ?

EDIT: Drive E is not mapped,it is just shared


Solution

  • This code worked very well

            Dim SharePath As String = "e:\Netuse"
            Dim SplitPath() As String = Split(SharePath, "\")
            Dim CurrentPath As String = String.Empty
            Dim ShareName As String = String.Empty
            Dim CurrentFolderIndex As Integer
            Dim UNCPath As String = String.Empty
    
            For CurrentFolderIndex = 0 To SplitPath.GetUpperBound(0)
                If CurrentPath = String.Empty Then
                    CurrentPath = String.Concat(SplitPath(CurrentFolderIndex), "\\")
                Else
                    CurrentPath += String.Concat(SplitPath(CurrentFolderIndex), "\\")
                End If
                ShareName = GetShareName(CurrentPath)
                If ShareName <> String.Empty Then
                    CurrentFolderIndex += 1
                    Exit For
                End If
            Next
    
            UNCPath = String.Concat("\\", My.Computer.Name, "\", ShareName)
    
            For SubPathIndex As Integer = CurrentFolderIndex To SplitPath.GetUpperBound(0)
                UNCPath = String.Concat(UNCPath, "\", SplitPath(SubPathIndex))
            Next
    
            Console.WriteLine(UNCPath)
    
    
    
        Public Function GetShareName(ByVal FolderPath As String) As String
    
            Dim Searcher As New ManagementObjectSearcher(String.Concat("select * from win32_share WHERE Path = '", FolderPath, "'"))
            Dim ShareName As String = String.Empty
    
            For Each Share As ManagementObject In Searcher.Get()
                ShareName = Share("Name").ToString
            Next
    
            Return ShareName
    
        End Function