Combine and resolve relative paths in C#

combining directory paths

Often it’s useful for a C# program to combine relative paths. For example, when you build a program in Visual Studio, the executable program runs in the bin\Debug subdirectory below the source code directory. If you want to manipulate a file that is in the same directory as the project’s source code, you need to move two level up the directory tree from the executable program’s location.

The System.IO.Path class provides several static methods for manipulating file paths. The Combine method combines two paths.

Unfortunately that method simply concatenates the paths. For example, C:\Data\Test plus ..\data.txt gives C:\Data\Test\..\data.txt, which is probably not what you want. The .. part of the path moves to the parent directory, so what you probably want in this example is C:\Data\data.txt.

Fortunately the Path class’s GetFullPath method resolves a path that contains relative elements such as this one and returns an absolute path.

The following code shows how the program combines two paths that you enter.

txtResult.Text = Path.GetFullPath(
    Path.Combine(txtPath1.Text, txtPath2.Text));

You can use a similar technique to combine paths in your programs. For example, a program running in Visual Studio can use the following code to find the path to its source code directory.

Console.WriteLine(Path.GetFullPath(
    Path.Combine(Application.StartupPath, "..\\..")));

Note that the GetFullPath method uses both the \ and / characters as directory delimiters, so the following code also works.

Console.WriteLine(Path.GetFullPath(
    Path.Combine(Application.StartupPath, "../..")));


Download Example   Follow me on Twitter   RSS feed


This entry was posted in files, system and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *