Quick Tip: Use System.IO.Path.Combine instead of string concatenation

I came across a bug in our application the other day. The code at fault was very similar to the simple example below.  It assumed that the 'folderPath' argument the code in question was supplied with already had a trailing '\' character appended to the folder path.  Because this was not always the case, the code was failing.  The fix was simple – I replaced the string concatenation with a call to System.IO.Path.Combine. This method takes care of checking for this situation and handles it for you. The System.IO.Path class is loaded with other methods that are useful when doing common file system operations.

kick it on DotNetKicks.com

using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string[] folderPaths = new string[] { @"c:\folder\folders", @"c:\folder\folders\" }; string fileName = "fileName.txt"; foreach (string folderPath in folderPaths) { Console.WriteLine(Program.SmartFileStringBuilder(folderPath, fileName)); Console.WriteLine(Program.LessSmartFileStringBuilder(folderPath, fileName)); } // both print the samething: c:\folder\folders\fileName.txt, one way is just a little more

// elegant than the other Console.Read(); } /// <summary> /// /// </summary> /// <param name="folderName"></param> /// <param name="fileName"></param> /// <returns></returns> private static string SmartFileStringBuilder(string folderName, string fileName) { return System.IO.Path.Combine(folderName, fileName); } /// <summary> /// /// </summary> /// <param name="folderName"></param> /// <param name="fileName"></param> /// <returns></returns> private static string LessSmartFileStringBuilder(string folderName, string fileName) { if (!folderName.EndsWith(@"\")) { folderName += @"\"; } return string.Format("{0}{1}", folderName, fileName); } } }


TrackBack

TrackBack URL for this entry:
http://mattberseth.com/blog-mt/mt-tb.fcgi/5

Listed below are links to weblogs that reference Quick Tip: Use System.IO.Path.Combine instead of string concatenation:

» Quick Tip: Use System.IO.Path.Combine instead of string concatenation from DotNetKicks.com
You've been kicked (a good thing) - Trackback from DotNetKicks.com [Read More]

Comments


Posted by: Anonymous on June 11, 2007 12:00 AM

cool tip

Just make sure you watch out for absolute paths in the second fragment. If you dont call IsRooted, you may end up with a different folder than you expected. Or even worse, a security hole.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)