Combining Directory Paths

When working with files it is typically to encounter the need to create a file path from two different strings. The basic way of doing this is to use a conditional statement and string concatenation. However, this is not recommended as it relies on system assumptions, like the directory separator character and that the paths contain valid characters.

.NET provides a static method, System.IO.Path.Combine(), that combines two strings to form a path and performs basic path checking. The word “basic” in the previous statement is very important as when using this method one has to be careful. The System.IO.Path.Combine() can be used both to combine paths for file I/O and to create search strings therefore it allows some invalid file characters to be used in the file paths.

Example 1:

Consider that a temporary file needs to be stored in the temporary folder location.

  1. using System.IO;
  2. using (StreamWriter streamWriter = new StreamWriter(Path.Combine(Path.GetTempFolder(), "myFile.txt")
  3. {
  4.     // Write to file
  5. }

The above code will create the file “myFile.txt” into the temporary folder. If for the purpose of this example, the temporary folder is assumed to be “C:\Temp” the output of the Path.Combine() method call will be “C:\Temp\myFile.txt”.

Example 2:

Now let’s consider that an invalid filename is passed to the function. This will throw an ArgumentException error.

  1. // Throws an ArgumentException error
  2. System.IO.Path.Combine("C:\\path 1", "this(is)a>wrong<file.txt");

The method System.IO.Path.Combine() is documented to throw two types of exceptions ArgumentException and ArgumentNullException. As a good practice one should always enclose the call into a try catch block.

  1. using System.IO;
  3. string combinedPath = string.Empty;
  4. try
  5. {
  6.     combinedPath = Path.Combine(path 1, path 2);
  7. }
  8. catch (ArgumentException aex)
  9. {
  10.     Console.Writeline("Error of type ArgumentException: {0}", aex.Message);
  11. }
  12. catch (ArgumentNullException anex)
  13. {
  14.     Console.Writeline("Error of the type ArgumentNullException: {0}", anex.Message);
  15. }