This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 1.1+

Building a File Path with Path.Combine

When using a variety of input methods to accept a file path and file name, the format of the results can vary. To avoid the problems of checking for path separator characters and adding or removing them as required, .NET provides a method to provide this.

System.IO Namespace

The System.IO namespace contains classes that provide input and output functionality for streams, files and folders. Within this namespace is the Path class, which performs operations on strings that contain file path information. One of the class's methods, named Combine, can be used to concatenate path fragments whilst automatically handling the problems of missing separator characters.

Using Path.Combine

The Combine method accepts two string parameters. Each is a fragment of a file path to be combined. The method appends the second parameter to the first and returns the new path according to the following rules.

  • If the first path is a drive letter only, eg. "C:", it remains unchanged.
  • If the first path is not just a drive letter, the combine method ensures that it ends with a separator character.
  • If the second parameter starts with a separator character it is assumed to be a root folder and is returned as the result of the entire operation.
  • If the second parameter does not start with a separator character it is appended to the first parameter.


The examples below demonstrate the four rules. Ensure that you have added using System.IO; to the start of your code file to execute the following:

Console.WriteLine(Path.Combine("d:", "file.txt"));
Console.WriteLine(Path.Combine(@"d:\", "file.txt"));
Console.WriteLine(Path.Combine(@"d:\path1", @"\file.txt"));
Console.WriteLine(Path.Combine(@"d:\path1", "file.txt"));
Console.WriteLine(Path.Combine(@"d:\path1\", "file.txt"));



4 November 2007