65.9K
CodeProject is changing. Read more.
Home

Convert a file path to a UNC Path

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 21, 2011

CPOL
viewsIcon

11891

Here is an API way using WNetGetUniversalNameImports System.Runtime.InteropServices _ Private Shared Function GetUName(ByVal Path As String, ByVal outName As Integer, ByVal bObj As...

Here is an API way using WNetGetUniversalName
Imports System.Runtime.InteropServices

  <DllImport("mpr.dll", Entrypoint:="WNetGetUniversalName", CharSet:=CharSet.Auto, SetLastError:=False)> _
  Private Shared Function GetUName(ByVal Path As String, ByVal outName As Integer, ByVal bObj As IntPtr, ByRef bSize As Integer) As Integer
  End Function
  <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto), Serializable()> Class UNIVERSAL_NAME_INFO
    <MarshalAs(UnmanagedType.LPTStr)> Public UniversalName As String
    <MarshalAs(UnmanagedType.LPTStr)> Public ConnectionName As String
    <MarshalAs(UnmanagedType.LPTStr)> Public RemainingPath As String
  End Class
  Dim size As Integer = 1024
  Dim buffer As IntPtr = Marshal.AllocHGlobal(size)

  Public Function getUNC(ByVal path As String)
    Dim uncpath As String = path
    Dim unc As New UNIVERSAL_NAME_INFO
    Dim ret As Int32 = GetUName(path, 1, buffer, size)
    If ret = 0 Then
      Marshal.PtrToStructure(buffer, unc)
      uncpath = unc.UniversalName
    End If
    Marshal.FreeHGlobal(buffer)
    Return uncpath
  End Function