Paths
Path is a static class of string operations on file names: it joins parts with the separator of the platform, takes a name apart, resolves a relative path against a folder and answers whether a path is rooted. It does not touch the file system, which is why every call in this lesson works on paths that do not exist.
Combine and the parts of a path
Path.Combine is the one call that must be used instead of a "/" between strings: it adds the separator of the platform and does not double one that is already there.
var combined = Path.Combine("reports", "2024", "march.csv");
Console.WriteLine(combined);
Console.WriteLine($"name {Path.GetFileName(combined)}");
Console.WriteLine($"stem {Path.GetFileNameWithoutExtension(combined)}");
Console.WriteLine($"extension {Path.GetExtension(combined)}");
Console.WriteLine($"dir {Path.GetDirectoryName(combined)}");
Console.WriteLine($"rooted {Path.IsPathRooted(combined)}");
Console.WriteLine($"rooted {Path.IsPathRooted("/etc/hosts")}");
Console.WriteLine($"changed {Path.ChangeExtension(combined, ".json")}");
Console.WriteLine($"separator {Path.DirectorySeparatorChar}");
Console.WriteLine($"temp {Path.GetTempPath()}");
dotnet run
reports/2024/march.csv
name march.csv
stem march
extension .csv
dir reports/2024
rooted False
rooted True
changed reports/2024/march.json
separator /
temp /tmp/
The separator is / on this system and would be \ on Windows, which is the reason for the call. A relative path is not rooted, an absolute one is, and GetTempPath returns the folder with the separator at its end. GetExtension returns the last suffix with its dot, so archive.tar.gz would give .gz.
Relative and absolute
A relative path is resolved against the current directory of the process. GetFullPath has an overload that takes the base folder explicitly, which makes the result independent of where the program was started:
var combined = Path.Combine("reports", "2024", "march.csv");
Console.WriteLine($"full {Path.GetFullPath(combined, "/srv/app")}");
Console.WriteLine($"relative {Path.GetRelativePath("/srv/app/reports", "/srv/app/reports/2024/march.csv")}");
dotnet run
full /srv/app/reports/2024/march.csv
relative 2024/march.csv
The two calls go in opposite directions: one turns a relative path into an absolute one, the other expresses one absolute path relative to a folder. A program that stores an absolute path in a file has a file that only works on that machine; a program that stores the relative one and resolves it against a configured base travels.
A path that names a file
The parts of a temporary path are still available after the file exists, which the next program shows on a path it built and then deleted:
var root = Path.Combine(Path.GetTempPath(), "aredel-paths");
if (Directory.Exists(root))
{
Directory.Delete(root, true);
}
var nested = Path.Combine(root, "in", "deeper");
Directory.CreateDirectory(nested);
var file = Path.Combine(nested, "data.txt");
File.WriteAllText(file, "x");
Console.WriteLine($"exists {File.Exists(file)}");
Console.WriteLine($"name {Path.GetFileName(file)}");
Console.WriteLine($"parts {string.Join("|", file.Split(Path.DirectorySeparatorChar)[^3..])}");
Console.WriteLine($"invalid {Path.GetInvalidFileNameChars().Length}");
Directory.Delete(root, true);
Console.WriteLine($"cleaned {!Directory.Exists(root)}");
dotnet run
exists True
name data.txt
parts in|deeper|data.txt
invalid 2
cleaned True
The path was built from parts, a folder chain was created, the file was written and the whole tree was deleted. The range at the end takes the last three parts of the array, which is what a reader usually wants from a long path.
What a file name may contain
Path.GetInvalidFileNameChars returns two characters on this system: the NUL byte and the slash. The colon that Windows forbids is a normal character here, so a name with one is a valid file name:
var bad = Path.Combine("/tmp", "bad:name.txt");
Console.WriteLine($"bad {bad}");
Console.WriteLine($"bad name {Path.GetFileName(bad)}");
dotnet run
bad /tmp/bad:name.txt
bad name bad:name.txt
A program that accepts a name from a user and builds a path from it must do more than check the invalid characters: a name of .. or an absolute path can leave the folder the program meant. The rule is to accept a name only when Path.GetFileName(name) equals the name itself, and to resolve the result against the intended folder before use.
Exercises
- Print the parts of /srv/app/reports/2024/march.csv one per line with Split.
- Resolve ../data/x.txt against /srv/app and print the result.
- Build the same path with Path.Combine and with string concatenation and compare them.
- Check whether Path.GetFileName of a name with a slash equals the name, for a safe and an unsafe input.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does Path.Combine do?
Answer
Joins the parts with the separator of the platform
It is a string operation with the platform separator, and it does not touch the disk.
-
What does this program print?
Console.WriteLine(Path.GetFileName("/srv/app/report.csv"));Answer
report.csv
GetFileName returns the last part of the path.
-
What does this program print?
Console.WriteLine(Path.GetExtension("archive.tar.gz"));Answer
.gz
The extension is the last suffix, with its dot.
-
Which call returns the folder part of a path?
Answer
Path.GetDirectoryName
The directory name is everything before the last separator.
-
What does this program print?
Console.WriteLine(Path.GetFileNameWithoutExtension("march.csv"));Answer
march
The extension and its dot are removed from the file name.
-
What does Path.GetTempPath return?
Answer
The temporary folder of the system, ending with a separator
It is /tmp/ here and the user temp folder on Windows.
-
Is a colon allowed in a file name on this system?
Answer
Yes, only NUL and the slash are invalid here
GetInvalidFileNameChars returned two characters, and the measured name kept its colon.
-
What does this program print?
Console.WriteLine(Path.Combine("reports", "2024"));Answer
reports/2024
The separator of this platform is the slash.
-
What does Path.GetFullPath(path, basePath) do?
Answer
Resolves a relative path against the given folder
The overload makes the result independent of the current directory.
-
What does this program print?
Console.WriteLine(Path.GetRelativePath("/srv/app", "/srv/app/reports/x.csv"));Answer
reports/x.csv
The second path is inside the first folder, so the relative form has no parent steps.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev