Combining paths in .Net

5 04 2009

Whenever you are combining paths using Path.Combine(path1, path2), watch out for a subtle but deadly pitfall.

path1 should not have a front slash at the end and path2 should not have a front slash in the beginning. Things get really bad otherwise. I have realized this after wasting 5-6 hours of precious weekend sleep. I can’t help cussing myself, because I have a feeling that I had made this mistake before. @#$@#!$@#$%@#!@#@!$. 🙂

i.e.
string path1 = "c:\\tempdir";
string path2 = "subdir\\";
path3=Path.Combine(path1, path2)
/*path3 = c:\\tempdir\\subdir\\*/

But,

string path1 = "c:\\tempdir";
string path2 = "\\subdir\\";
path3=Path.Combine(path1, path2)
/*path3 = \\subdir\\*/

In my defense, I strongly feel that the library function should have taken care of this subtle variation. (Blame .Net 🙂 )

Anyways, find more information about this function here.

Advertisements