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

IT researcher picture IT researcher · Apr 24, 2013 · Viewed 13.1k times · Source

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

Answer

Cubsoft picture Cubsoft · Apr 24, 2013

Just created a small app which seems to work.

It takes a textbox with a non-unc value and converts it,then sets a label

Remember to include the following namespaces if you haven't already;

Imports System.Text
Imports System.IO

This is the method that does all the work;

Private Function GetUNCPath(ByVal sFilePath As String) As String

Dim allDrives() As DriveInfo = DriveInfo.GetDrives()
Dim d As DriveInfo
Dim DriveType, Ctr As Integer
Dim DriveLtr, UNCName As String
Dim StrBldr As New StringBuilder

If sFilePath.StartsWith("\\") Then Return sFilePath

UNCName = Space(160)
GetUNCPath = ""

DriveLtr = sFilePath.Substring(0, 3)

For Each d In allDrives
  If d.Name = DriveLtr Then
    DriveType = d.DriveType
    Exit For
  End If
Next

If DriveType = 4 Then

  Ctr = WNetGetConnection(sFilePath.Substring(0, 2), UNCName, UNCName.Length)

  If Ctr = 0 Then
    UNCName = UNCName.Trim
    For Ctr = 0 To UNCName.Length - 1
      Dim SingleChar As Char = UNCName(Ctr)
      Dim asciiValue As Integer = Asc(SingleChar)
      If asciiValue > 0 Then
        StrBldr.Append(SingleChar)
      Else
        Exit For
      End If
    Next
    StrBldr.Append(sFilePath.Substring(2))
    GetUNCPath = StrBldr.ToString
  Else
    MsgBox("Cannot Retrieve UNC path" & vbCrLf & "Must Use Mapped Drive of SQLServer", MsgBoxStyle.Critical)
  End If
Else
  MsgBox("Cannot Use Local Drive" & vbCrLf & "Must Use Mapped Drive of SQLServer", MsgBoxStyle.Critical)
End If

End Function

Declare this function;

  Declare Function WNetGetConnection Lib "mpr.dll" Alias "WNetGetConnectionA" (ByVal lpszLocalName As String, _
       ByVal lpszRemoteName As String, ByRef cbRemoteName As Integer) As Integer

Call the code from a button click;

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
     Dim RealFileName As String = GetUNCPath(txtFileName.Text)
     lblUNC.Text = RealFileName
  End Sub

Hope this helps.