将路径转换为UNC路径

本文关键字:路径 UNC 转换 | 更新日期: 2023-09-27 18:17:47

我已经尝试了这个代码将我的路径转换为UNC路径:

[DllImport("mpr.dll", CharSet = CharSet.Unicode)]
[return:MarshalAs(UnmanagedType.U4)]
static extern int WNetGetUniversalName(
    string lpLocalPath,
    [MarshalAs(UnmanagedType.U4)] int dwInfoLevel,
    IntPtr lpBuffer,
    [MarshalAs(UnmanagedType.U4)] ref int lpBufferSize);
const int UNIVERSAL_NAME_INFO_LEVEL = 0x00000001;
const int REMOTE_NAME_INFO_LEVEL = 0x00000002;
const int ERROR_MORE_DATA = 234;
const int NOERROR = 0;    
static string GetUniversalName(string localPath)
{
    // The return value.
    string retVal = null ;
    // The pointer in memory to the structure.
    IntPtr buffer = IntPtr.Zero;
    // Wrap in a try/catch block for cleanup.
    try
    {
        // First, call WNetGetUniversalName to get the size.
        int size = 0;
        // Make the call.
        // Pass IntPtr.Size because the API doesn't like null, even though
        // size is zero.  We know that IntPtr.Size will be
        // aligned correctly.
        int apiRetVal = WNetGetUniversalName(localPath, UNIVERSAL_NAME_INFO_LEVEL, (IntPtr) IntPtr.Size, ref size);
        // If the return value is not ERROR_MORE_DATA, then
        // raise an exception.
        if (apiRetVal != ERROR_MORE_DATA)
            // Throw an exception.
            throw new Win32Exception(apiRetVal);
        // Allocate the memory.
        buffer = Marshal.AllocCoTaskMem(size);
        // Now make the call.
        apiRetVal = WNetGetUniversalName(localPath, UNIVERSAL_NAME_INFO_LEVEL, buffer, ref size);
        // If it didn't succeed, then throw.
        if (apiRetVal != NOERROR)
            // Throw an exception.
            throw new Win32Exception(apiRetVal);
        // Now get the string.  It's all in the same buffer, but
        // the pointer is first, so offset the pointer by IntPtr.Size
        // and pass to PtrToStringAnsi.
        retVal = Marshal.PtrToStringAuto(new IntPtr(buffer.ToInt64() + IntPtr.Size), size);
        retVal = retVal.Substring(0, retVal.IndexOf(''0'));
    }
    finally
    {
        // Release the buffer.
        Marshal.FreeCoTaskMem(buffer);
    }
    // First, allocate the memory for the structure.
    // That's all folks.
    return retVal;
}

但是当我发送路径''myservername'sharedfoldername到这个方法时,我收到这个错误:

指定的设备名无效。

我错在哪里?

将路径转换为UNC路径

From MSDN(强调我的):

WNetGetUniversalName函数为网络资源获取基于驱动器的路径,并返回包含更通用形式的名称的信息结构。

你正在传递一个UNC路径,但是函数期望一个基于驱动器的路径(例如X:'foo'bar),然后返回一个UNC路径

指定的设备名无效。

据我所知,当WNetGetUniversalName()获得本地驱动器的路径时,它还返回ERROR_BAD_DEVICE_PATH。

所以,三年前,我理解这个返回代码如下;

ERROR_BAD_DEVICE_PATH:
请检查路径是否真的需要更改为UNC名称