Get the physical path of a path that uses a subst drive
My previous employer used a tool to attach databases that were located on a substituted path. I needed this conversion logic in another kind of environment and used the almighty google. So I hit an article on Avner Kashtan
's blog titled Query SUBST information
. His code sample proved very usefull but it didn't support relative paths on the current drive so I altered it a bit. Below is my version and put it here for other people to use and abuse.
public static class Subst
public static string GetRealPath(string path)
const string MSG_PATH_INVALID = "The path/file specified does not exist.";
const int BUFFER_LENGTH = 1024;
if (path == null) throw new ArgumentNullException("path");
path = new DirectoryInfo(path).FullName;
else if (File.Exists(path))
path = new FileInfo(path).FullName;
throw new ArgumentException(MSG_PATH_INVALID, "path");
string realPath = path;
StringBuilder pathInformation = new StringBuilder(BUFFER_LENGTH);
string driveLetter = Path.GetPathRoot(realPath).Replace(@"\", string.Empty);
QueryDosDevice(driveLetter, pathInformation, BUFFER_LENGTH);
// If drive is substed, the result will be in the format of "\??\C:\RealPath\".
// after that strip the \??\ prefix and combine the paths.
string realRoot = pathInformation.ToString(4, pathInformation.Length-4);
realPath = realRoot + realPath.Substring(2); // Remove the drive letter
static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);
I tried to use Manoli's csharp to HTML formatter but it screws up. So no syntax coloring this time.