Convert a relative path that includes a drive letter to an absolute path for .NET file functions

.net, .net-4.0, c#, c#-4.0

Solution

You could use `GetFullPath`. For example:

// should return "D:\data\test.xml" if the current working dir is "D:\data"
string absolutePath = Path.GetFullPath("D:test.xml");

If the CWD is `"D:\Data"`, `Path.GetFullPath("D:test.xml")` would indeed return `"D:\data\test.xml"`, as it would getting full path directly for "test.xml".

However, if using a different drive letter than the one used for the CWD, the result will not be consistent. For example `Path.GetFullPath("C:test.xml")` would return `"C:\test.xml".`

This is by design. Take a look at http://msdn.microsoft.com/en-us/library/aa365247.aspx#fully_qualified_vs._relative_paths.

If a file name begins with only a disk designator but not the backslash after the colon, it is interpreted as a relative path to the current directory on the drive with the specified letter. Note that the current directory may or may not be the root directory depending on what it was set to during the most recent "change directory" operation on that disk.

[Emphasis added by me]

Problem

How can you convert a drive relative path such as `D:test.xml` into an absolute path that a function such as `XDocument.Load()` will accept. The D drive could have `D:\data` as its current working directory, for example, so `D:test.xml` would mean `D:\data\test.xml` . I've already tried such concoctions as `D:.\test.xml` . Here is the error I get for something like `D:test.xml`: Invalid URI: A Dos path must be rooted, for example, 'c:\'

Original source