C# – XPath and Converting a Relative Path to Absolute

Star Ocean - The Last HopeToday whilst doing some C# programming, I came by a path within a file that was relative to the path I was reading it from. Since my application wasn’t in the same place, and I didn’t want it to be be for it to be, I needed to convert it to an absolute path.

This is C#, it should be simple right?

Well apparently System.IO.Path.Combine() doesn’t take into account “./” or “../” and just concatenates and added an additional forward slash if needed.

After a bit of searching, and many different examples (most of which just converted absolute to relative), I found what I needed. This method used System.IO.Path.GetFullPath() with System.IO.Path.Combine() (If I used the relative path on its own with GetFullPath() I just got the relative path from the current executable directory).

I made it into a single function I can call but I was surprised that there wasn’t something already to do this considering what C# has impressed me with so far for thinking ahead.

//
//
using System.IO;
 
//
//
static string GetAbsoluteFromRelative( string inBasePath, string inRelativePath )
{
	return Path.GetFullPath( Path.Combine( inBasePath, inRelativePath ) );
}

 

It hasn’t tainted my image of C# though, I still adore it for its XML XPath node iterator library thing that has MySQL searching features.

I also found a spiffy thing I didn’t know about XPath as well. If I have a set of data like so.

<FileList>

<Folder>

<File>MyFile</File>

</Folder>

<File>MyOtherFile</File>

</FileList>

I can iterate through all file nodes within file list with a double-slash before “File” within my node select call.

XPathNavigator nav;
 
// ...
 
XPathNodeIterator fileNodes = nav.Select("/FileList//File");
 
while( fileNodes.MoveNext() )
{
	Console.WriteLine( fileNodes.Current.Value );
}

 

I still seem to have problems with namespaces in some XML documents though (ones without them seem to make searching a hassle).