ZetCode

C# Path

last modified November 6, 2026

In this article we show how to work with paths using the Path class in C#.

Path is a static class in the System.IO namespace. Its methods take a path string apart, put paths together, and convert between relative and absolute paths. Almost all of them work only with strings: they do not check whether the file or directory exists. The rules follow the operating system the program runs on, so the same code gives different results on Windows and on Unix.

The outputs in this article come from Linux, so the examples use Unix paths.

Parts of a path

The first example splits a path into its parts.

Program.cs
string path = Path.Combine("/var", "log", "app", "server.2026-03.log");

Console.WriteLine($"path: {path}");
Console.WriteLine($"GetFileName: {Path.GetFileName(path)}");
Console.WriteLine($"GetFileNameWithoutExtension: {Path.GetFileNameWithoutExtension(path)}");
Console.WriteLine($"GetExtension: {Path.GetExtension(path)}");
Console.WriteLine($"HasExtension: {Path.HasExtension(path)}");
Console.WriteLine($"GetDirectoryName: {Path.GetDirectoryName(path)}");
Console.WriteLine($"GetPathRoot: {Path.GetPathRoot(path)}");

Console.WriteLine($"GetDirectoryName of root: {Path.GetDirectoryName("/") ?? "null"}");
Console.WriteLine($"GetFileName of directory path: '{Path.GetFileName("/var/log/")}'");

We build a path with Path.Combine and print its parts.

Console.WriteLine($"GetFileNameWithoutExtension: {Path.GetFileNameWithoutExtension(path)}");
Console.WriteLine($"GetExtension: {Path.GetExtension(path)}");

The extension is the part after the last dot, including the dot. Other dots belong to the file name.

Console.WriteLine($"GetDirectoryName: {Path.GetDirectoryName(path)}");

GetDirectoryName returns everything before the last separator.

Console.WriteLine($"GetDirectoryName of root: {Path.GetDirectoryName("/") ?? "null"}");
Console.WriteLine($"GetFileName of directory path: '{Path.GetFileName("/var/log/")}'");

For a root, GetDirectoryName returns null. A path that ends with a separator has an empty file name, because the methods only look at the characters.

$ dotnet run
path: /var/log/app/server.2026-03.log
GetFileName: server.2026-03.log
GetFileNameWithoutExtension: server.2026-03
GetExtension: .log
HasExtension: True
GetDirectoryName: /var/log/app
GetPathRoot: /
GetDirectoryName of root: null
GetFileName of directory path: ''

Combine and Join

Path.Combine and Path.Join both put path parts together with the correct separator. They differ in how they treat rooted parts.

Program.cs
Console.WriteLine(Path.Combine("data", "2026", "report.csv"));
Console.WriteLine(Path.Combine("data/", "report.csv"));

Console.WriteLine(Path.Combine("/srv/uploads", "/etc/passwd"));
Console.WriteLine(Path.Join("/srv/uploads", "/etc/passwd"));

Console.WriteLine(Path.Join("data", "", "report.csv"));
Console.WriteLine(Path.Join("data", "..", "report.csv"));

We join several parts with both methods.

Console.WriteLine(Path.Combine("data/", "report.csv"));

A separator is added only where it is missing.

Console.WriteLine(Path.Combine("/srv/uploads", "/etc/passwd"));
Console.WriteLine(Path.Join("/srv/uploads", "/etc/passwd"));

When a later part is an absolute path, Combine discards everything before it. If the second part comes from user input, this lets the user point anywhere in the file system. Join, added in .NET Core 3.0, simply concatenates the parts.

Console.WriteLine(Path.Join("data", "..", "report.csv"));

Neither method resolves .. segments; that is done by GetFullPath. Join also skips empty parts, as the fifth line of the output shows.

$ dotnet run
data/2026/report.csv
data/report.csv
/etc/passwd
/srv/uploads/etc/passwd
data/report.csv
data/../report.csv

Extensions

ChangeExtension replaces the extension of a path.

Program.cs
string path = Path.Combine("reports", "sales.2026.txt");

Console.WriteLine(Path.ChangeExtension(path, ".csv"));
Console.WriteLine(Path.ChangeExtension(path, "csv"));
Console.WriteLine(Path.ChangeExtension(path, ".bak.txt"));
Console.WriteLine(Path.ChangeExtension(path, ""));
Console.WriteLine(Path.ChangeExtension(path, null));

Console.WriteLine($"'{Path.GetExtension(".gitignore")}'");
Console.WriteLine($"'{Path.GetExtension("archive.tar.gz")}'");
Console.WriteLine($"'{Path.GetExtension("Makefile")}'");

We change the extension of a file name that contains several dots.

Console.WriteLine(Path.ChangeExtension(path, ".csv"));
Console.WriteLine(Path.ChangeExtension(path, "csv"));

The new extension may be given with or without the leading dot. Only the part after the last dot is replaced.

Console.WriteLine(Path.ChangeExtension(path, ""));
Console.WriteLine(Path.ChangeExtension(path, null));

An empty string leaves a trailing dot, while null removes the extension with its dot.

Console.WriteLine($"'{Path.GetExtension(".gitignore")}'");
Console.WriteLine($"'{Path.GetExtension("archive.tar.gz")}'");

For .gitignore, the whole name counts as the extension. Double extensions such as .tar.gz are not recognized.

$ dotnet run
reports/sales.2026.csv
reports/sales.2026.csv
reports/sales.2026.bak.txt
reports/sales.2026.
reports/sales.2026
'.gitignore'
'.gz'
''

Full and relative paths

GetFullPath turns a relative path into an absolute one and GetRelativePath does the opposite.

Program.cs
string basePath = "/home/user/projects/app";

Console.WriteLine(Path.GetFullPath("src/../tests/./unit", basePath));
Console.WriteLine(Path.GetFullPath("../../music", basePath));
Console.WriteLine(Path.GetFullPath("/etc/hosts", basePath));

Console.WriteLine(Path.GetRelativePath(basePath, "/home/user/projects/app/src/main.cs"));
Console.WriteLine(Path.GetRelativePath(basePath, "/home/user/documents/notes.txt"));

Console.WriteLine(Path.IsPathRooted("/etc/hosts"));
Console.WriteLine(Path.IsPathFullyQualified("/etc/hosts"));
Console.WriteLine(Path.IsPathRooted("docs/readme.md"));

We resolve paths against a base directory and compute paths relative to it.

Console.WriteLine(Path.GetFullPath("src/../tests/./unit", basePath));

The overload with a base path, added in .NET Core 2.1, resolves the path against the given directory instead of the working directory. It also removes the . and .. segments.

Console.WriteLine(Path.GetRelativePath(basePath, "/home/user/documents/notes.txt"));

GetRelativePath uses .. to go up when the target is outside the base directory.

Console.WriteLine(Path.IsPathRooted("/etc/hosts"));
Console.WriteLine(Path.IsPathFullyQualified("/etc/hosts"));

On Unix, a rooted path is also fully qualified. On Windows, they differ: \data is rooted but not fully qualified, because it is relative to the current drive.

$ dotnet run
/home/user/projects/app/tests/unit
/home/user/music
/etc/hosts
src/main.cs
../../documents/notes.txt
True
True
False

Keeping paths inside a directory

A program that serves or stores files under a root directory must make sure that a name from the user cannot escape it, an attack known as path traversal.

Program.cs
string root = Path.GetFullPath("/srv/uploads");

foreach (string name in new[] { "photo.jpg", "2026/march/photo.jpg", "../../etc/passwd", "/etc/passwd", "a/../../uploads2/x" })
{
    string? path = ResolveUnder(root, name);
    Console.WriteLine($"{name,-22} -> {path ?? "rejected"}");
}

static string? ResolveUnder(string root, string relative)
{
    string full = Path.GetFullPath(Path.Join(root, relative));
    string prefix = Path.EndsInDirectorySeparator(root) ? root : root + Path.DirectorySeparatorChar;

    return full.StartsWith(prefix, StringComparison.Ordinal) ? full : null;
}

The ResolveUnder method returns the full path of a name inside the root, or null if the name leads outside.

string full = Path.GetFullPath(Path.Join(root, relative));

Join keeps absolute names under the root, and GetFullPath resolves the .. segments.

string prefix = Path.EndsInDirectorySeparator(root) ? root : root + Path.DirectorySeparatorChar;

The prefix ends with a separator, so that /srv/uploads2 is not accepted as a path inside /srv/uploads. On Windows, use a case-insensitive comparison. Symbolic links inside the root can still point outside it; for full protection, check the resolved target of the opened file.

$ dotnet run
photo.jpg              -> /srv/uploads/photo.jpg
2026/march/photo.jpg   -> /srv/uploads/2026/march/photo.jpg
../../etc/passwd       -> rejected
/etc/passwd            -> /srv/uploads/etc/passwd
a/../../uploads2/x     -> rejected

Temporary files and names

The Path class gives the temporary directory and creates temporary names.

Program.cs
Console.WriteLine($"temp directory: {Path.GetTempPath()}");

string random = Path.GetRandomFileName();
Console.WriteLine($"random name: {random}, exists: {File.Exists(random)}");

string tempFile = Path.GetTempFileName();
Console.WriteLine($"temp file: {Path.GetFileName(tempFile)}, exists: {File.Exists(tempFile)}, size: {new FileInfo(tempFile).Length}");
File.Delete(tempFile);

DirectoryInfo tempDir = Directory.CreateTempSubdirectory("build-");
Console.WriteLine($"temp subdirectory: {tempDir.Name}");
tempDir.Delete(true);

We print the temporary directory and create a random name, a temporary file, and a temporary directory.

string random = Path.GetRandomFileName();

GetRandomFileName returns a random name in the 8.3 format. It does not create a file.

string tempFile = Path.GetTempFileName();

GetTempFileName creates an empty file in the temporary directory and returns its path. The caller is responsible for deleting it.

DirectoryInfo tempDir = Directory.CreateTempSubdirectory("build-");

For a temporary directory, .NET 7 added Directory.CreateTempSubdirectory, which creates a directory with a unique name and an optional prefix.

$ dotnet run
temp directory: /tmp/
random name: 4iw2tc5k.ohh, exists: False
temp file: tmp8vCgAm.tmp, exists: True, size: 0
temp subdirectory: build-BeOJNt

Separators and platforms

The separator characters differ between operating systems.

Program.cs
Console.WriteLine($"DirectorySeparatorChar: '{Path.DirectorySeparatorChar}'");
Console.WriteLine($"AltDirectorySeparatorChar: '{Path.AltDirectorySeparatorChar}'");
Console.WriteLine($"PathSeparator: '{Path.PathSeparator}'");
Console.WriteLine($"VolumeSeparatorChar: '{Path.VolumeSeparatorChar}'");

string windowsPath = @"C:\data\report.txt";
Console.WriteLine($"GetFileName: {Path.GetFileName(windowsPath)}");
Console.WriteLine($"IsPathRooted: {Path.IsPathRooted(windowsPath)}");

string? pathVar = Environment.GetEnvironmentVariable("PATH");
Console.WriteLine($"PATH entries: {pathVar?.Split(Path.PathSeparator).Length}");

Console.WriteLine(Path.TrimEndingDirectorySeparator("/var/log/"));
Console.WriteLine(Path.EndsInDirectorySeparator("/var/log/"));

We print the separators and look at a Windows path on Linux.

Console.WriteLine($"DirectorySeparatorChar: '{Path.DirectorySeparatorChar}'");
Console.WriteLine($"AltDirectorySeparatorChar: '{Path.AltDirectorySeparatorChar}'");

On Windows, the separator is the backslash and the alternative is the slash; both work. On Unix, both properties are the slash.

string windowsPath = @"C:\data\report.txt";
Console.WriteLine($"GetFileName: {Path.GetFileName(windowsPath)}");

On Linux, the backslash is an ordinary character that may appear in file names, so the whole Windows path is one file name and it is not rooted. Write paths with Path.Combine or Path.Join, or with slashes, instead of hard-coding backslashes.

Console.WriteLine($"PATH entries: {pathVar?.Split(Path.PathSeparator).Length}");

PathSeparator separates the entries of the PATH environment variable: a colon on Unix and a semicolon on Windows.

$ dotnet run
DirectorySeparatorChar: '/'
AltDirectorySeparatorChar: '/'
PathSeparator: ':'
VolumeSeparatorChar: '/'
GetFileName: C:\data\report.txt
IsPathRooted: False
PATH entries: 65
/var/log
True

Safe file names

Text from users or documents often contains characters that are not allowed in file names.

Program.cs
char[] invalid = Path.GetInvalidFileNameChars();
Console.WriteLine($"invalid file name characters: {invalid.Length}");
Console.WriteLine(string.Join(", ", invalid.Select(c => $"0x{(int)c:X2}")));

foreach (string title in new[] { "Q1/Q2 results", "notes: draft", "report" })
{
    Console.WriteLine($"{title} -> {ToFileName(title)}.txt");
}

static string ToFileName(string text)
{
    char[] bad = [.. Path.GetInvalidFileNameChars(), '\\', ':', '*', '?', '"', '<', '>', '|'];
    return string.Concat(text.Select(c => bad.Contains(c) ? '_' : c));
}

We print the characters that are invalid on this platform and convert titles into file names.

char[] invalid = Path.GetInvalidFileNameChars();

On Linux, only the null character and the slash are invalid. Windows forbids more characters, including \ : * ? " < > | and control characters.

char[] bad = [.. Path.GetInvalidFileNameChars(), '\\', ':', '*', '?', '"', '<', '>', '|'];

To create names that work on every system, we add the Windows characters to the list and replace all of them with an underscore.

$ dotnet run
invalid file name characters: 2
0x00, 0x2F
Q1/Q2 results -> Q1_Q2 results.txt
notes: draft -> notes_ draft.txt
report -> report.txt

Source

Path class

In this article we have worked with paths using the Path class in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.