如果您想查看所有映射驱动器及其解析路径的列表:
Console.WriteLine(String.Join(Environment.NewLine,
GetUNCDrives().Select(kvp =>
string.Format("{0} => {1}", kvp.Key, kvp.Value))));
如果您想获取路径的可能更短分辨率的列表:
var longPath = @"\\HarddiskVolume2\ent\RRPSTO\foobar\file.txt";
Console.WriteLine(string.Join(Environment.NewLine, GetShortPaths(longPath)));
如果您只是假设只有一个映射驱动器分辨率,您可以选择第一个:
var shortPaths = GetShortPaths(longPath);
var path = shortPaths.Length > 0 ? shortPaths[0] : longPath;
或者您可以根据网络地图的深度从列表中进行选择。因此,要获得最短的映射路径(不是最短路径名),您只需计算路径中有多少“/”。
或者你可以作弊,只取路径名最短的那个。不过,这并不能保证是最简单的路径。
无论您想怎么做,下面的代码都是使上面的代码工作的原因。
你需要这些人:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.IO;
您还需要在项目引用中包含System.Management.dll。
代码:
/// <summary>Gets array of all possible shorter paths for provided path.</summary>
/// <param name="path">The path to find alternate addresses for.</param>
static string[] GetShortPaths(string path)
{
return GetUNCDrives()
.Where(kvp => path.StartsWith(kvp.Value))
.Select(kvp => Path.Combine(kvp.Key, path.Substring(kvp.Value.Length + 1)))
.ToArray();
}
/// <summary>Gets all mapped drives and resolved paths.</summary>
/// <returns>Dictionary: Key = drive, Value = resolved path</returns>
static Dictionary<string, string> GetUNCDrives()
{
return DriveInfo.GetDrives()
.Where(di => di.DriveType == DriveType.Network)
.ToDictionary(di => di.RootDirectory.FullName
, di => GetUNCPath(di.RootDirectory.FullName.Substring(0, 2)));
}
/// <summary>Attempts to resolve the path/root to mapped value.</summary>
/// <param name="path">The path to resolve.</param>
static string GetUNCPath(string path)
{
if (path.StartsWith(@"\\"))
return path;
var mo = new ManagementObject(string.Format("Win32_LogicalDisk='{0}'", path));
return Convert.ToUInt32(mo["DriveType"]) == (UInt32)DriveType.Network
? Convert.ToString(mo["ProviderName"])
: path;
}