System.IO.Path.Combine Method

Combines two strings into a path.

Syntax

public static string Combine (string path1, string path2)

Parameters

path1
The first path to combine.
path2
The second path to combine.

Returns

The combined paths. If one of the specified paths is a zero-length string, this method returns the other path. If path2 contains an absolute path, this method returns path2.

Exceptions

TypeReason
ArgumentNullException path1 or path2 is null.
ArgumentException path1 or path2 contains one or more implementation-specific invalid characters.

Remarks

If path1 is not a drive reference (that is, "C:" or "D:") and does not end with a valid separator character as defined in Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, or Path.VolumeSeparatorChar, Path.DirectorySeparatorChar is appended to path1 before concatenation.

If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.

The parameters are not parsed if they have white space. Therefore, if path2 includes white space (for example, " c:\\ "), the Path.Combine(string, string) method appends path2 to path1 instead of returning only path2.

Not all invalid characters for directory and file names are interpreted as unacceptable by the Combine method, because you can use these characters for search wildcard characters. For example, while Path.Combine("c:\\", "*.txt") might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the Combine method.

For a list of common I/O tasks, see Common I/O Tasks.

Example

The following example demonstrates using the Combine method on a Windows system.

C# Example

using System;
using System.IO;
class CombineTest {
 public static void Main() {
 string path1, path2;
 Console.WriteLine("Dir char is {0} Alt dir char is {1}",
 Path.DirectorySeparatorChar,
 Path.AltDirectorySeparatorChar
 );
 path1 = "foo.txt";
 path2 = "\\ecmatest\\examples";
 Console.WriteLine("{0} combined with {1} = {2}",path1, path2 , Path.Combine(path1, 

path2));
 path1 = "\\ecmatest\\examples";
 path2 = "foo.txt";
 Console.WriteLine("{0} combined with {1} = {2}",path1, path2 , Path.Combine(path1, 

path2));
 }
}
   

The output is

Dir char is \ Alt dir char is /
foo.txt combined with \ecmatest\examples = \ecmatest\examples
\ecmatest\examples combined with foo.txt = \ecmatest\examples\foo.txt

Requirements

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0