A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Friday, March 26, 2010

Yes Virgina, there is a .NET path builder

In the .NET world, if you are gluing paths together with string concatenation, or some reasonable facsimile thereof, STOP.  I know I'm not the only one who didn't know this method existed in the framework as I see plenty of code with "System.IO.File.Open(basePath + fileName, System.IO.FileMode.Open);"  In the python world, it was easy open(os.path.join(basePath, fileName)).

What's the problem?  Directory separators.  In the Windows world, it's a slash \.  In the C#/C++/C world, \ is also the beginnings of an escape sequence.  If I wanted a string that held a newline (return/enter), a tab, a bell, etc, I would have to encode that with an escaped sequence like \n, \t, \a  Despite two characters there, it's a 1 character size.  What does escaping have to do with building directory paths?  The true problem is consistency.  Do you store your path with a trailing slash or not?  The coding above assumes basePath has a trailing slash but what about the people using your method?  Perhaps they aren't versed in using the raw/literal string (the at sign @ in path1) so they are going to save themselves the two extra keystrokes to add the trailing slahes as shown in path2 below.  Over time, that simple string concatenation will grow to look for trailing slashes, adding where it's required, doing some monkey patching when there are quotes etc.  

If you have your own library and you love using it, by all means, keep it up.  As for me and the code I review, we're going with System.IO.Path.Combine  If you click through to the Combine method on that link, they have a much larger example of using Combine but this snippet should suffice to show the proper way to build the path.

string fileName = @"Zapotec.bmp";
string path1 = @"C:\windows";
string path2 = "C:\\windows\\";
string path3 = @"C:\windows\";
Console.WriteLine(System.IO.Path.Combine(path1, fileName));
Console.WriteLine(System.IO.Path.Combine(path2, fileName));
Console.WriteLine(System.IO.Path.Combine(path3, fileName));

No comments: