Get UNC path from a local path or mapped path

送分小仙女□ 提交于 2019-12-01 16:50:37

There is no built-in function in the BCL which will do the equivalent. I think the best option you have is pInvoking into WNetGetConnection as you suggested.

P/Invoke WNetGetUniversalName().

I've done it modifying this code from www.pinvoke.net.

Here's some C# code with a wrapper function LocalToUNC, which seems to work OK, though I haven't tested it extensively.

    [DllImport("mpr.dll")]
    static extern int WNetGetUniversalNameA(
        string lpLocalPath, int dwInfoLevel, IntPtr lpBuffer, ref int lpBufferSize
    );

    // I think max length for UNC is actually 32,767
    static string LocalToUNC(string localPath, int maxLen = 2000)
    {
        IntPtr lpBuff;

        // Allocate the memory
        try
        {
            lpBuff = Marshal.AllocHGlobal(maxLen); 
        }
        catch (OutOfMemoryException)
        {
            return null;
        }

        try
        {
            int res = WNetGetUniversalNameA(localPath, 1, lpBuff, ref maxLen);

            if (res != 0)
                return null;

            // lpbuff is a structure, whose first element is a pointer to the UNC name (just going to be lpBuff + sizeof(int))
            return Marshal.PtrToStringAnsi(Marshal.ReadIntPtr(lpBuff));
        }
        catch (Exception)
        {
            return null;
        }
        finally
        {
            Marshal.FreeHGlobal(lpBuff);
        }
    }

Try this code, is written in Delphi .Net

you must translate it to c #

function WNetGetUniversalName; external;
[SuppressUnmanagedCodeSecurity, DllImport(mpr, CharSet = CharSet.Ansi, SetLastError = True, EntryPoint = 'WNetGetUniversalNameA')]


function ExpandUNCFileName(const FileName: string): string;

function GetUniversalName(const FileName: string): string;
const
UNIVERSAL_NAME_INFO_LEVEL = 1;    
var
  Buffer: IntPtr;
  BufSize: DWORD;
begin
  Result := FileName;
  BufSize := 1024;
  Buffer := Marshal.AllocHGlobal(BufSize);
  try
    if WNetGetUniversalName(FileName, UNIVERSAL_NAME_INFO_LEVEL,
      Buffer, BufSize) <> NO_ERROR then Exit;
    Result := TUniversalNameInfo(Marshal.PtrToStructure(Buffer,
      TypeOf(TUniversalNameInfo))).lpUniversalName;
  finally
    Marshal.FreeHGlobal(Buffer);
  end;
end;

begin
  Result :=System.IO.Path.GetFullPath(FileName);
  if (Length(Result) >= 3) and (Result[2] = ':') and (Upcase(Result[1]) >= 'A')
    and (Upcase(Result[1]) <= 'Z') then
    Result := GetUniversalName(Result);
end;

Bye.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!