Reputation: 96947
How do I join two file paths in C#?
Upvotes: 117
Views: 57076
Reputation:
Path.Join Method
Join(String, String)
class Program
{
static void Main()
{
ShowPathInformation("C:/", "users/user1/documents", "letters");
ShowPathInformation("D:/", "/users/user1/documents", "letters");
ShowPathInformation("D:/", "users/user1/documents", "C:/users/user1/documents/data");
}
private static void ShowPathInformation(string path1, string path2, string path3)
{
Console.WriteLine($"Concatenating '{path1}', '{path2}', and '{path3}'");
Console.WriteLine($" Path.Join: '{Path.Join(path1, path2, path3)}'");
Console.WriteLine($" Path.Combine: '{Path.Combine(path1, path2, path3)}'");
Console.WriteLine($" {Path.GetFullPath(Path.Join(path1, path2, path3))}");
}
}
// The example displays the following output if run on a Windows system:
// Concatenating 'C:/', 'users/user1/documents', and 'letters'
// Path.Join: 'C:/users/user1/documents\letters'
// Path.Combine: 'C:/users/user1/documents\letters'
// C:\users\user1\documents\letters
// Concatenating 'D:/', '/users/user1/documents', and 'letters'
// Path.Join: 'D://users/user1/documents\letters'
// Path.Combine: '/users/user1/documents\letters'
// D:\users\user1\documents\letters
// Concatenating 'D:/', 'users/user1/documents', and 'C:/users/user1/documents/data'
// Path.Join: 'D:/users/user1/documents\C:/users/user1/documents/data'
// Path.Combine: 'C:/users/user1/documents/data'
// D:\users\user1\documents\C:\users\user1\documents\data
Unlike the Combine method, the Join method does not attempt to root the returned path. (That is, if path2 or path2 is an absolute path, the Join method does not discard the previous paths as the Combine method does.
Not all invalid characters for directory and file names are interpreted as unacceptable by the Join method, because you can use these characters for search wildcard characters. For example, while Path.Join("c:\", "temp", "*.txt") might be invalid when creating a file, it is valid as a search string. The Join method therefore successfully interprets it.
Upvotes: 7
Reputation: 71936
System.IO.Path.Combine() is what you need.
Path.Combine(path1, path2);
Upvotes: 38
Reputation: 51538
You have to use Path.Combine() as in the example below:
string basePath = @"c:\temp";
string filePath = "test.txt";
string combinedPath = Path.Combine(basePath, filePath);
// produces c:\temp\test.txt
Upvotes: 179