Tuesday, December 4, 2007

Using Path.Combine instead of string concatenation

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/using_pathcombine_instead_of_string_concatenation.htm]

I often need to work with filePaths, such as getting an absolute file name given a directory and a fileName. One way for developers to do this is simply string concatenation. A lot of devs do this because it appears so simple. But the problem is that when passing in the directory as a string, you often don't know if it will end with a final slash or not - i.e "C:\Temp" or "C:\Temp\". Merely doing string concat will screw it up, you could get a non-existent file like "C:\Temp\\MyFile.txt".


A much better approach is to use System.IO.Path.Combine. This allows you to have a directory (with or without the slash), and the combine method if smart enough to handle it:

    public static string GetFileName(string strDir, string strName)
      //return strDir + @"\" + strName;   //BAD
      return System.IO.Path.Combine(strDir, strName); //GOOD


What's funny is that both options are just 1 line of code and take essentially the exact same amount of time to write. However, the first is very brittle, and could likely cost you tons of time tracking down an error because someone passed in a directory with or without that extra slash. The second just works.

No comments:

Post a Comment