UNC Path Convert to Local Path

最近用到FSRM,发现无法识别UNC路径,因此写了这段转义Code。

static string ConvertUNC2Local(string UNC)
{
    Dictionary<string, string> UncLocal = new Dictionary<string, string>();
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_share");
    foreach (ManagementObject obj in searcher.Get())
    {
        string name = (string)obj.Properties["Name"].Value;
        string local = (string)obj.Properties["Path"].Value;
        UncLocal.Add(name.ToLower(), local);
    }
    string rootPath;
    string[] shareNameAndRelativePath = GetShareNameAndRelativePath(UNC);
    if (!UncLocal.TryGetValue(shareNameAndRelativePath[0].ToLower(), out rootPath))
    {
        Console.WriteLine("The UNC you input is not local path.");
        return string.Empty;
    }
    else
    {
        return Path.Combine(rootPath, shareNameAndRelativePath[1]);
    }
}

static string[] GetShareNameAndRelativePath(string UNC)
{
    string[] result = new string[2];
    Regex reg = new Regex(@"\d\\");
    MatchCollection mc = reg.Matches(UNC);
    int index = mc[0].Index + 2;
    int nextIndex = UNC.IndexOf('\\', index);
    int length = nextIndex - index;
    result[0] = UNC.Substring(index, length);
    result[1] = UNC.Substring(nextIndex + 1);
    return result;
}
原文地址:https://www.cnblogs.com/hazy/p/4846988.html