For some odd reason, System.IO doesn’t include a method to get the UNC path for a file or directory. Even stranger, many code samples resort to using p/invoke in order to get that information. But then I came across this StackOverflow answer that explained a pure .NET way to do the same thing. I gave the original code a good refactoring and turned it into the extension method below. While the most obvious place to stick something like this is the Path class, since it’s static that’s not possible. Instead, I opted to add it to the FileInfo class. But it could just as easily be added to DirectoryInfo.

Note: In order to use this code, you’ll need a reference to System.Management.dll.

public static class Extensions
{
	public static string UncPath(this FileInfo fileInfo)
	{
		string filePath = fileInfo.FullName;

		if (filePath.StartsWith(@"\\"))
			return filePath;

		if (new DriveInfo(Path.GetPathRoot(filePath)).DriveType != DriveType.Network)
			return filePath;

		string drivePrefix = Path.GetPathRoot(filePath).Substring(0, 2);
		string uncRoot;

		using (var managementObject = new ManagementObject())
		{
		    var managementPath = string.Format("Win32_LogicalDisk='{0}'", drivePrefix);
			managementObject.Path = new ManagementPath(managementPath);
			uncRoot = (string)managementObject["ProviderName"];
		}

		return filePath.Replace(drivePrefix, uncRoot);
	}
}