Getting started
editInstall the package
Add the Meziantou.Framework.FullPath package to a project:
dotnet package add Meziantou.Framework.FullPathThe package also adds the analyzer to C# projects. The examples of this documentation omit the using directives: they need using Meziantou.Framework;.
Create and use paths
Create a path, combine it with the / operator, and pass it to the file APIs:
FullPath root = FullPath.FromFileSystemInfo(Directory.CreateTempSubdirectory());
// Combine paths with the / operator
FullPath settings = root / "config" / "settings.json";
Assert.Equal("settings.json", settings.Name);
Assert.Equal(root / "config", settings.Parent);
// FullPath converts to string implicitly, so it works with every API that takes a path
settings.CreateParentDirectory();
File.WriteAllText(settings, "{}");
Assert.True(File.Exists(settings));
// Show the path relative to the root folder (config/settings.json, or config\settings.json on Windows)
Assert.Equal(Path.Combine("config", "settings.json"), settings.MakePathRelativeTo(root));- FullPath.FromFileSystemInfo converts the
DirectoryInfothatDirectory.CreateTempSubdirectoryreturns. FullPath.FromPath converts a string. - The
/operator appends one or more segments to a path. It returns a new FullPath. - Name and Parent read the parts of the path, without accessing the file system.
- CreateParentDirectory creates the folder that contains the file, and its own parents, when they do not exist.
File.WriteAllTexttakes a string: the FullPath converts to it implicitly.
Store paths as FullPath
Declare your fields, properties, parameters and return values as FullPath rather than string. The type then documents that the value is an absolute path, and the conversion happens once, where the path enters the application: a command-line argument, a configuration value, a JSON document.
The analyzer finds the strings that only ever hold a FullPath: see Declaring FullPath instead of string.
Next steps
- Creating paths: the ways to create a path, and how it is normalized.
- Comparing paths: equality, case sensitivity and collections.
- Analyzer: convert existing code.