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.
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); } } }
Comments
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.