C-SHARP - 5.5 Path
The Path class from the System.IO namespace groups static utility methods for working with strings that represent file or folder paths. It never touches the file system - it only works on the string itself. Its main benefit: producing portable paths and avoiding separator mistakes between Windows (\) and Unix (/).
Combining and splitting a path
Path.Combine assembles several parts using the correct separator for the current platform. Conversely, several methods extract a piece from an existing path:
using System.IO;
string path = Path.Combine("C:", "Users", "Documents", "report.pdf");
// "C:\Users\Documents\report.pdf" on Windows
string name = Path.GetFileName(path); // "report.pdf"
string noExt = Path.GetFileNameWithoutExtension(path); // "report"
string ext = Path.GetExtension(path); // ".pdf"
string folder = Path.GetDirectoryName(path); // "C:\Users\Documents"
string root = Path.GetPathRoot(path); // "C:\"
Handy common methods
Path.HasExtension(path): returnstrueif the path has an extension.Path.ChangeExtension(path, ".txt"): replaces the current extension.Path.IsPathRooted(path): tells you whether the path is absolute.Path.GetFullPath(relative): converts a relative path into an absolute one.Path.GetTempFileName(): creates a unique temporary file and returns its path.
Why prefer Path over manual concatenation
Building a path with + or string interpolation is error-prone: missing separators, doubled ones (//), Windows/Linux incompatibilities. Path.Combine handles all of that automatically and keeps your code portable. Make it a habit now: any time you work with a path, go through Path.