Thursday, March 13, 2003

Path.Combine

I often see people using string concatenation to create directory names. Like this:


string path = "C:\\data\\" + filename;


But there's a much better API:


string path = System.IO.Path.Combine("C:\\data", filename);


Not only does this take care of the whole, "Do I need a trailing slash?" issue, but if you specify an absolute path for the second parameter, it will just return the second parameter. That means that someone can enter "foo" or "C:\\temp\\foo" for filename, and it'll do what you'd expect.

8 comments:

  1. I should second that but... What about c# on non ms platforms? I mean a lot of code i see just hardcode the path separator and even more, some of them make assumptions on the disk letter or the disk separator... Path contains very nifty fields to handle that.

    ReplyDelete
  2. Yeah, no kidding. I didn't mention it explicitly, but that's an excellent point.

    ReplyDelete
  3. You missed the interesting fact that if path2 has a leading backslash ("\filename.txt"), it is interpreted as an absolute path - for some reason. This makes this method basically useless, to me. If the method is called "Path.Combine", it would be more intuitive if it actually always combined the paths, just cutting of drive letters and making sure that slashes are correct. Useless, pretty much.

    ReplyDelete
  4. Umm, if it has a leading backslash, it *is* an absolute path. Drive-relative, to be sure, but not every OS supports the concept of drive letters.



    Sorry you don't find it useful, but in my book, if it didn't behave this way, it would be broken.

    ReplyDelete
  5. Just use TrimStart('\').TrimStart('/') of the string class to get rid of that annoying absolute path bug. And yes, I'll maintain it is a bug. I sure as heck wouldn't put anything that'd be an absolute path in the second field. And in the off chance that it was necessary, let them put in checks for that rare case, rather than screw us over on the common case.

    ReplyDelete
  6. Well, the change you suggest would definitely break some of my code, so I'm hoping they don't "fix" it. :)



    If you think it's a bug you should file it at the Product Feedback Center. The dev teams take that stuff seriously.

    ReplyDelete
  7. Actually, this isn't so much a bug as it is a poorly named method.



    The method needs a new name, or at least the parameters should be renamed. See:

    http://geekswithblogs.net/dchestnutt/archive/2007/03/13/108682.aspx

    ReplyDelete
  8. Here is a C# open-source library that helps handling complex path scenario such as relative/absolute conversion, rebasing, and much more

    http://www.codeplex.com/FileDirectoryPath

    ReplyDelete