ZetCode

C# Path

last modified November 15, 2026

This article shows how to work with file and directory paths in C# using the Path class.

The static Path class from the System.IO namespace operates on path strings. It extracts parts of a path, combines paths, resolves relative paths, and creates names for temporary files. Most of its methods do not touch the file system at all; they only parse and build strings. This is why Path.GetFileName works for a file that does not exist.

Each operating system has its own path conventions. Windows uses \ as the directory separator and drive letters like C:, while Linux and macOS use / and a single root. The Path class follows the rules of the platform the program runs on. The examples in this article were run on Linux; the same code works on Windows, but some outputs differ, as noted in the text.

Method Description
Combine, Join Join path segments into one path.
GetFileName, GetFileNameWithoutExtension Return the last segment of a path.
GetDirectoryName Returns the path without its last segment.
GetExtension, HasExtension, ChangeExtension Work with the file extension.
GetFullPath Returns an absolute, normalized path.
GetRelativePath Returns a path relative to another one.
GetPathRoot, IsPathRooted, IsPathFullyQualified Work with the root of a path.
GetTempPath, GetTempFileName, GetRandomFileName Temporary directory and file names.
Exists Checks if a file or directory exists (.NET 7).

C# Path separators

The Path class has fields with the separator characters of the current platform.

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

var paths = Environment.GetEnvironmentVariable("PATH") ?? "";
Console.WriteLine(paths.Split(Path.PathSeparator).Length > 0);

We print the separators.

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

On Linux, both directory separators are /. On Windows, the primary separator is \ and the alternative one is /; Windows accepts both.

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

The path separator divides the entries of the PATH environment variable. It is : on Unix systems and ; on Windows. The volume separator is : on Windows, as in C:; on Linux it has the value /.

$ dotnet run
DirectorySeparatorChar: /
AltDirectorySeparatorChar: /
PathSeparator: :
VolumeSeparatorChar: /
True

C# Path parts

Several methods extract parts of a path: the root, the directory, the file name, and the extension.

Program.cs
var path = "/home/user/docs/report.final.pdf";

Console.WriteLine($"Root: {Path.GetPathRoot(path)}");
Console.WriteLine($"Directory: {Path.GetDirectoryName(path)}");
Console.WriteLine($"File name: {Path.GetFileName(path)}");
Console.WriteLine($"Without extension: {Path.GetFileNameWithoutExtension(path)}");
Console.WriteLine($"Extension: {Path.GetExtension(path)}");
Console.WriteLine($"Has extension: {Path.HasExtension(path)}");

Console.WriteLine($"[{Path.GetFileName("/home/user/docs/")}]");
Console.WriteLine($"[{Path.GetDirectoryName("/home/user/docs/")}]");
Console.WriteLine($"[{Path.GetExtension(".bashrc")}]");
Console.WriteLine(Path.GetDirectoryName("/") is null);

We split a path into its parts and look at a few edge cases.

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

The extension is the part after the last dot, including the dot. For "report.final.pdf", the name without extension is "report.final".

Console.WriteLine($"[{Path.GetFileName("/home/user/docs/")}]");
Console.WriteLine($"[{Path.GetDirectoryName("/home/user/docs/")}]");

The methods only look at the characters. A path that ends with a separator has an empty file name, and its directory name is the path without the trailing separator.

Console.WriteLine($"[{Path.GetExtension(".bashrc")}]");

A hidden Unix file like ".bashrc" has no name before the dot, so the whole name is treated as the extension.

Console.WriteLine(Path.GetDirectoryName("/") is null);

For a root directory, GetDirectoryName returns null.

$ dotnet run
Root: /
Directory: /home/user/docs
File name: report.final.pdf
Without extension: report.final
Extension: .pdf
Has extension: True
[]
[/home/user/docs]
[.bashrc]
True

C# Path.ChangeExtension

ChangeExtension returns the path with a different extension. The file itself is not renamed.

Program.cs
var path = "/home/user/docs/words.txt";

Console.WriteLine(Path.ChangeExtension(path, "bak"));
Console.WriteLine(Path.ChangeExtension(path, ".md"));
Console.WriteLine(Path.ChangeExtension(path, null));
Console.WriteLine(Path.ChangeExtension("archive.tar.gz", "zip"));

We change the extension of several paths.

Console.WriteLine(Path.ChangeExtension(path, "bak"));
Console.WriteLine(Path.ChangeExtension(path, ".md"));

The new extension can be given with or without the leading dot.

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

Passing null removes the extension.

Console.WriteLine(Path.ChangeExtension("archive.tar.gz", "zip"));

Only the last extension is replaced, which gives the odd "archive.tar.zip".

$ dotnet run
/home/user/docs/words.bak
/home/user/docs/words.md
/home/user/docs/words
archive.tar.zip

C# Path.Combine and Path.Join

Combine and Join concatenate path segments and add separators where needed. They differ in how they treat rooted segments.

Program.cs
Console.WriteLine(Path.Combine("/home", "user", "words.txt"));
Console.WriteLine(Path.Combine("/home/user/", "docs/", "words.txt"));

Console.WriteLine(Path.Combine("/home/user", "/etc/passwd"));
Console.WriteLine(Path.Join("/home/user", "/etc/passwd"));

Console.WriteLine(Path.Join("/home/user/", "/docs", "words.txt"));
Console.WriteLine(Path.Join("/home/user", "", "words.txt"));

We combine paths with both methods.

Console.WriteLine(Path.Combine("/home/user/", "docs/", "words.txt"));

A separator is added only if the segment does not already end with one.

Console.WriteLine(Path.Combine("/home/user", "/etc/passwd"));
Console.WriteLine(Path.Join("/home/user", "/etc/passwd"));

When a later segment is rooted, Combine discards everything before it and returns "/etc/passwd". Join (.NET Core 3.0) simply concatenates the segments. This matters when a segment comes from the user, as we will see below.

Console.WriteLine(Path.Join("/home/user/", "/docs", "words.txt"));

Join does not remove duplicate separators, so this path has two slashes. The operating system accepts it, and GetFullPath removes the extra slash.

$ dotnet run
/home/user/words.txt
/home/user/docs/words.txt
/etc/passwd
/home/user/etc/passwd
/home/user//docs/words.txt
/home/user/words.txt

C# Path.GetFullPath

GetFullPath turns a relative path into an absolute one and normalizes it: it resolves the . and .. segments and removes duplicate separators. It does not check that the path exists.

Program.cs
Directory.SetCurrentDirectory("/tmp");

Console.WriteLine(Path.GetFullPath("."));
Console.WriteLine(Path.GetFullPath("data/words.txt"));
Console.WriteLine(Path.GetFullPath("../etc/hosts"));
Console.WriteLine(Path.GetFullPath("/home/user/../user/docs/./file.txt"));
Console.WriteLine(Path.GetFullPath("/home//user///docs"));

Console.WriteLine(Path.GetFullPath("docs/words.txt", "/home/user"));

We resolve several relative and messy paths.

Directory.SetCurrentDirectory("/tmp");

Relative paths are resolved against the current directory. We set it to /tmp so that the output is predictable.

Console.WriteLine(Path.GetFullPath("/home/user/../user/docs/./file.txt"));
Console.WriteLine(Path.GetFullPath("/home//user///docs"));

The redundant segments and slashes are removed.

Console.WriteLine(Path.GetFullPath("docs/words.txt", "/home/user"));

The overload with a second argument (.NET Core 2.1) resolves the path against the given base directory instead of the current directory. This is safer in libraries, since the current directory is global state that any part of the program can change.

$ dotnet run
/tmp
/tmp/data/words.txt
/etc/hosts
/home/user/docs/file.txt
/home/user/docs
/home/user/docs/words.txt

C# rooted and fully qualified paths

IsPathRooted checks if a path starts with a root. IsPathFullyQualified checks if the path is fixed and does not depend on the current directory or drive.

Program.cs
string[] paths = ["/home/user/words.txt", "words.txt", "./words.txt",
    "../words.txt", "~/words.txt", @"C:\Users\words.txt", @"\\server\share"];

foreach (var p in paths)
{
    Console.WriteLine($"{p,-22} rooted: {Path.IsPathRooted(p),-5} " +
        $"fully qualified: {Path.IsPathFullyQualified(p)}");
}

We test both methods on Unix and Windows style paths.

"../words.txt", "~/words.txt", @"C:\Users\words.txt", @"\\server\share"];

On Linux, only paths that start with / are rooted. The tilde is a shell feature; for .NET it is an ordinary character, so "~/words.txt" is a relative path. Windows paths are not rooted on Linux because the backslash is a valid file name character there. On Windows, "C:\Users\words.txt" and "\\server\share" are fully qualified, while "\words.txt" is rooted but not fully qualified, because it depends on the current drive.

$ dotnet run
/home/user/words.txt   rooted: True  fully qualified: True
words.txt              rooted: False fully qualified: False
./words.txt            rooted: False fully qualified: False
../words.txt           rooted: False fully qualified: False
~/words.txt            rooted: False fully qualified: False
C:\Users\words.txt     rooted: False fully qualified: False
\\server\share         rooted: False fully qualified: False

C# Path.GetRelativePath

GetRelativePath computes the path from one directory to another.

Program.cs
var basePath = "/home/user/docs";

Console.WriteLine(Path.GetRelativePath(basePath, "/home/user/docs/projects/words.txt"));
Console.WriteLine(Path.GetRelativePath(basePath, "/home/user/music/song.mp3"));
Console.WriteLine(Path.GetRelativePath(basePath, "/etc/hosts"));
Console.WriteLine(Path.GetRelativePath(basePath, basePath));

We compute paths relative to "/home/user/docs".

Console.WriteLine(Path.GetRelativePath(basePath, "/home/user/music/song.mp3"));

When the target is outside the base directory, the result starts with .. segments. The paths are compared as strings; the method does not follow symbolic links.

Console.WriteLine(Path.GetRelativePath(basePath, basePath));

A directory relative to itself is ".".

$ dotnet run
projects/words.txt
../music/song.mp3
../../../etc/hosts
.

C# Path with spans

Many Path methods have overloads that take and return ReadOnlySpan<char>. They avoid allocating new strings, which helps in code that processes many paths.

Program.cs
ReadOnlySpan<char> dir = "/home/user/docs";
ReadOnlySpan<char> file = "words.txt";

Span<char> buffer = stackalloc char[64];

if (Path.TryJoin(dir, file, buffer, out int written))
{
    Console.WriteLine(buffer[..written].ToString());
}

Span<char> small = stackalloc char[10];
Console.WriteLine(Path.TryJoin(dir, file, small, out written));

ReadOnlySpan<char> path = "/home/user/docs/words.txt";
ReadOnlySpan<char> name = Path.GetFileNameWithoutExtension(path);
Console.WriteLine(name.ToString());

We join two segments into a stack-allocated buffer and extract a file name without creating a string.

if (Path.TryJoin(dir, file, buffer, out int written))
{
    Console.WriteLine(buffer[..written].ToString());
}

TryJoin writes the result into the destination span and returns the number of characters written. Only the first written characters of the buffer belong to the path.

Console.WriteLine(Path.TryJoin(dir, file, small, out written));

If the buffer is too small, TryJoin returns false instead of throwing.

ReadOnlySpan<char> name = Path.GetFileNameWithoutExtension(path);

The span overload returns a slice of the input; no string is created until we call ToString.

$ dotnet run
/home/user/docs/words.txt
False
words

C# invalid file name characters

GetInvalidFileNameChars returns the characters that are not allowed in file names on the current platform.

Program.cs
var invalid = Path.GetInvalidFileNameChars();
Console.WriteLine($"{invalid.Length} invalid file name chars");
Console.WriteLine(string.Join(" ", invalid.Select(c => $"U+{(int)c:X4}")));

Console.WriteLine($"{Path.GetInvalidPathChars().Length} invalid path chars");

string[] names = ["notes.txt", "my:file|v2?.txt", "a/b.txt", "bad\0name"];

foreach (var name in names)
{
    bool ok = name.IndexOfAny(invalid) == -1;
    Console.WriteLine($"{name.Replace("\0", "\\0"),-16} {(ok ? "valid" : "invalid")}");
}

We print the invalid characters and check several names.

Console.WriteLine(string.Join(" ", invalid.Select(c => $"U+{(int)c:X4}")));

On Linux, only two characters are forbidden in a file name: the null character and the slash. On Windows, the list has 41 characters, including the control characters and " < > | : * ? \ /.

bool ok = name.IndexOfAny(invalid) == -1;

The name "my:file|v2?.txt" is valid on Linux, but it could not be created on Windows. If files are shared between systems, check for the Windows set of characters explicitly. Also note that the list is not a complete validation; Windows also reserves names like CON or NUL.

$ dotnet run
2 invalid file name chars
U+0000 U+002F
1 invalid path chars
notes.txt        valid
my:file|v2?.txt  valid
a/b.txt          invalid
bad\0name        invalid

C# combine user input safely

Joining a user-supplied name to a base directory is a common source of security bugs. A name like "../../etc/passwd" escapes the directory, and Path.Combine with a rooted name ignores the base directory completely.

Program.cs
const string uploads = "/srv/app/uploads";

string[] inputs = ["notes.txt", "docs/notes.txt", "../../etc/passwd",
    "/etc/passwd", "docs/../../uploads2/x"];

foreach (var input in inputs)
{
    Console.WriteLine($"{input,-24} {Resolve(uploads, input) ?? "rejected"}");
}

static string? Resolve(string baseDir, string userPath)
{
    var root = Path.GetFullPath(baseDir);

    if (!Path.EndsInDirectorySeparator(root))
    {
        root += Path.DirectorySeparatorChar;
    }

    var full = Path.GetFullPath(Path.Join(root, userPath));

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

The Resolve function returns the full path only if it stays inside the base directory.

var full = Path.GetFullPath(Path.Join(root, userPath));

We use Join, which keeps the base directory even for a rooted input, and normalize the result with GetFullPath, which resolves all .. segments.

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

The normalized path must start with the base directory. The base ends with a separator; otherwise "/srv/app/uploads2/x" would pass the check, because it starts with "/srv/app/uploads". On Windows, which has case-insensitive file names, use StringComparison.OrdinalIgnoreCase. The input "/etc/passwd" is accepted, but it is placed inside the uploads directory.

$ dotnet run
notes.txt                /srv/app/uploads/notes.txt
docs/notes.txt           /srv/app/uploads/docs/notes.txt
../../etc/passwd         rejected
/etc/passwd              /srv/app/uploads/etc/passwd
docs/../../uploads2/x    rejected

C# temporary files

GetTempPath returns the temporary directory of the user and GetRandomFileName a random name. GetTempFileName creates an empty file with a unique name.

Program.cs
var name = Path.GetRandomFileName();
Console.WriteLine(name);

var tempDir = Path.GetTempPath();
Console.WriteLine(tempDir);

var tempFile = Path.Combine(tempDir, Path.GetRandomFileName());
File.WriteAllText(tempFile, "temporary data");
Console.WriteLine(Path.Exists(tempFile));

File.Delete(tempFile);
Console.WriteLine(Path.Exists(tempFile));

var tmp = Path.GetTempFileName();
Console.WriteLine($"{Path.GetFileName(tmp)} {new FileInfo(tmp).Length} bytes");
File.Delete(tmp);

We create and delete temporary files.

var name = Path.GetRandomFileName();

GetRandomFileName returns a random 8.3 name generated with a cryptographically strong random number generator. It only returns a string; no file is created.

var tempDir = Path.GetTempPath();

On Linux, the temporary directory is taken from the TMPDIR environment variable, with "/tmp/" as the fallback. On Windows, it is usually in the user's AppData folder.

Console.WriteLine(Path.Exists(tempFile));

Path.Exists (.NET 7) returns true for an existing file or directory.

var tmp = Path.GetTempFileName();

GetTempFileName creates a zero-byte file and returns its path. We are responsible for deleting it.

$ dotnet run
4qxczseu.a50
/tmp/
True
False
tmpmGw6vU.tmp 0 bytes

C# split a path into segments

There is no method that returns all segments of a path, but we can split the string or walk up the tree with GetDirectoryName.

Program.cs
var path = "/home/user/docs/report.pdf";

var parts = path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(string.Join(" | ", parts));

for (string? p = path; p is not null; p = Path.GetDirectoryName(p))
{
    Console.WriteLine(p);
}

Console.WriteLine(Path.TrimEndingDirectorySeparator("/home/user/docs/"));
Console.WriteLine(Path.EndsInDirectorySeparator("/home/user/docs/"));

We split a path in two ways.

var parts = path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);

Splitting by the separator gives the individual segments. The empty entry before the leading slash is removed.

for (string? p = path; p is not null; p = Path.GetDirectoryName(p))
{
    Console.WriteLine(p);
}

Calling GetDirectoryName repeatedly walks up to the root, where it returns null and the loop ends.

Console.WriteLine(Path.TrimEndingDirectorySeparator("/home/user/docs/"));

TrimEndingDirectorySeparator and EndsInDirectorySeparator (.NET Core 3.0) handle trailing separators; the root "/" is never trimmed.

$ dotnet run
home | user | docs | report.pdf
/home/user/docs/report.pdf
/home/user/docs
/home/user
/home
/
/home/user/docs
True

Source

Path class - .NET API

File path formats on Windows systems - .NET

In this article we have worked with paths in C# using the Path class. See also the Path class reference article and the File, Directory, and FileInfo tutorials.

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.