Working with paths in C#

Time and time again when working with code that involves operations with the file system a developer may write something like

var path = @"C:\Temp";
var file = @"file.txt";
var pathToFile = path + "\\" + file;
// pathToFile = "C:\\Temp\\file.txt"

In an ideal world every developer would be using Path.Combine and would write something similar to

var path = @"C:\Temp";
var file = @"file.txt";
var pathToFile = System.IO.Path.Combine(path, file);
// pathToFile = "C:\\Temp\\file.txt";

Path.Combine has a number of advantages over string concatenation, for instance it will

  • Remove superflous directory separators
  • Use the directory seperator for the system it is running on
  • This can be particularly useful if you are using C# in mono on OSX or Linux
  • Prevent illegal paths like C:\Temp\C:\file.txt being created

One area where it can fall down however is combining two file paths, one absolute and one relative. An issue can arise when the relative file path starts with . or ..

var path = @"C:\Temp";
var file = @"..\file.txt";
var pathToFile = System.IO.Path.Combine(path, file);
// pathToFile = "C:\\Temp\\..\\file.txt";

It is clear that the file being referred to here is actually C:\file.txt but the combination of the paths did not pick up on the change in directory and how it would affect the overall path.

This can be fixed using Path.GetFullPath

var path = @"C:\Temp";
var file = @"..\file.txt";
var pathToFile = System.IO.Path.Combine(path, file);
// pathToFile = "C:\\Temp\\..\\file.txt

var fullPath = System.IO.Path.GetFullPath(pathToFile);
// fullPath = "C:\\file.txt"

This can help prevent unexpected issues by sanitising the file path, and just as importantly it's clearer from the outset what file the system is looking for which can only be of help to yourself.