Get the physical path of a path that uses a subst drive

By ramon
April 5, 2007
1

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.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

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");
if (Directory.Exists(path))
{
path = new DirectoryInfo(path).FullName;
}
else if (File.Exists(path))
{
path = new FileInfo(path).FullName;
}
else
{
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.
if (pathInformation.ToString().Contains(@"??"))
{
string realRoot = pathInformation.ToString(4, pathInformation.Length-4);
realPath = realRoot + realPath.Substring(2); // Remove the drive letter
}

return realPath;
}

[DllImport("kernel32.dll")]
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.

Comments: 1

  1. If I would have the sourcecode of your code then I probably would have used that as a base for this implementation :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta