.NN#9: Simple but Handy

This weeks .Net Nugget is very straight forward and perhaps many of you already know about this little gem: System.IO.Path.

How many times have you seen code like this?

string fullFilePath = string.Empty;
if (filePath.EndsWith("\"))
{
    fullFilePath = string.Concat(filePath, fileName);
}
else
{
    fullFilePath = string.Concat(filePath, “\”, fileName);
}

This code is determining if a string that represents a file path ends with a trailing backslash.  If it does then it simply populates the fullFilePath variable with the string concatenation of the file path and file name.  If it doesn’t then it concatenates them both separated by a slash.

A couple of things here…first off, how many times have you seen code that was concatenating a path and file name together that didn’t take this into account.  I’ve seen it more times than I care to think about.  Some of the assume the slash will be included and others assume it won’t be.  I guess it’s a fifty-fifty shot.  Second, this code is error prone and most likely repeated in a lot of places (unless you have pulled it out into a helper function). 

Luckily a helper function basically is built in the framework!  System.IO.Path.Combine will combine the two path strings and deal with the separators for you.  So the code above could be expressed completely as:

string fullFilePath = System.IO.Path.Combine(filePath, fileName);

Another cool thing is that the Path functions are all platform specific, so if this code gets ported to MONO, etc. the correct directory separators will be used.

Path has several useful methods, but one thing to note is that almost none of the methods actually touch the file system.  Almost all of them revolve around just validating a path (it’s syntax if you will) or working against a path in string format.  It doesn’t validate that a path exists or anything like that.

I know this .NN is a little light on depth, but hey….I’m on vacation!

[NOTE: for the VB.Net people out there the double backslashes in the code is on purpose as the backslash is an escape character in C#]