从本地路径或映射路径获取UNC路径

Chr*_*s J 7 c# unc

在Delphi中有一个函数ExpandUNCFileName,它接受一个文件名并将其转换为UNC等价物.它扩展了映射驱动器并跳过本地和已扩展的位置.

样品

C:\ Folder\Text.txt - > C:\ Folder\Text.txt
L:\ Folder\Sample.txt - > \\ server\Folder1\Folder\Sample.txt其中L:映射到\\ server\Folder1\
\\服务器\文件夹\ Sample.odf - > \服务器\文件夹\ Sample.odf

有没有一种简单的方法在C#中执行此操作或者我是否必须使用Windows api调用WNetGetConnection然后手动检查那些无法映射的?

Jay*_*ggs 5

P/Invoke WNetGetUniversalName().

我已经从www.pinvoke.net 修改了这段代码.


小智 5

这里有一些带有包装函数LocalToUNC的C#代码,虽然我没有对它进行过广泛的测试,但它似乎工作正常.

    [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);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Jar*_*Par 2

BCL 中没有内置函数可以执行相同的操作。我认为您最好的选择是按照您的建议 pInvoking into WNetGetConnection 。