File System File System
File System File System
DocFX + Singulink = ♥

Search Results for

    PathOptions

    PathOptions is a flags enum that controls how strictly path strings are validated during parsing. Every parse method, every IDirectoryPath.CombineDirectory / IDirectoryPath.CombineFile overload that takes a string, and every extension-related method accepts a PathOptions value and uses NoUnfriendlyNames when none is given. That default exists to protect you from path strings that are technically valid in some file systems but reliably cause trouble in real-world code, so loosen it only when you have a clear reason.

    Default: NoUnfriendlyNames

    NoUnfriendlyNames is the recommended default for almost all application code. It is a combination of:

    • NoReservedDeviceNames
    • NoLeadingSpaces
    • NoTrailingSpaces
    • NoTrailingDots
    • NoControlCharacters

    Any of those patterns will cause parsing to throw ArgumentException with a precise message about why the path was rejected (the Try parse methods return false instead).

    FilePath.ParseAbsolute(@"C:\data \report.pdf");   // throws: entry name "data " ends with a space
    FilePath.ParseAbsolute(@"C:\nul");                // throws: reserved device name
    FilePath.ParseAbsolute(@"C:\data\file.");         // throws: entry name ends with a dot
    
    Tip

    If your code is rejecting valid-looking paths and you don't know why, the exception message names the exact rule that fired. Use that to decide whether to fix the input or relax the option.

    Individual Flags

    None

    PathOptions.None allows every path that is technically valid for the given format. Use this when you must work with whatever the file system contains, for example, paths returned by an OS file picker or paths read directly from an existing file system.

    string filePathString = openFileDialog.FileName;
    var file = FilePath.ParseAbsolute(filePathString, PathOptions.None);
    file.OpenStream();
    
    Caution

    Don't store user-supplied "unfriendly" paths and re-display them later without care. Leading and trailing spaces are invisible in most UI; round-tripping a path string through a control that trims whitespace will produce a different path that points at a different file.

    AllowEmptyDirectories

    By default, a//b (two consecutive separators producing an empty segment) is rejected because it is almost always a bug, for example a missing variable expansion. Set AllowEmptyDirectories to silently collapse the empty segment instead:

    DirectoryPath.ParseRelative("path/to//some/dir");                                    // throws
    DirectoryPath.ParseRelative("path/to//some/dir", PathOptions.AllowEmptyDirectories); // "path/to/some/dir/"
    

    NoReservedDeviceNames

    NoReservedDeviceNames rejects entry names that match Windows reserved device names: CON, PRN, AUX, NUL, COM1-COM9, LPT1-LPT9. Has no effect when parsing with PathFormat.Unix.

    NoLeadingSpaces / NoTrailingSpaces

    NoLeadingSpaces and NoTrailingSpaces reject entry names with a leading or trailing space. These names break Windows File Explorer, are difficult to handle in UI/serialization, and are a frequent source of silent failures in System.IO.

    Only the very start and end of each entry name are checked. A space before the extension, as in report .pdf, is neither leading nor trailing and is accepted.

    NoTrailingDots

    NoTrailingDots rejects entry names ending in .. Same rationale as above: Windows applications typically can't handle these reliably.

    NoNavigation

    NoNavigation rejects any path that contains . or .. segments and rejects rooted-relative paths (e.g. \Some\Path on Windows). Use this when you parse paths from untrusted input that must remain inside a known directory:

    // Reject "../../etc/passwd" style inputs up front:
    var safe = FilePath.ParseRelative(userInput, PathOptions.NoUnfriendlyNames | PathOptions.NoNavigation);
    
    Important

    NoNavigation is a parse-time check. It does not by itself sandbox a path. Combine the parsed relative path with a known-safe absolute base directory before doing any I/O.

    NoControlCharacters

    NoControlCharacters rejects characters with ASCII codes 1-31 in entry names. Has no effect on PathFormat.Windows (where these are always disallowed).

    PathFormatDependent

    PathFormatDependent is a modifier flag. When set, the NoUnfriendlyNames rules get appended when the path's format is PathFormat.Windows or PathFormat.Universal, and are left out for PathFormat.Unix. Use this when you want your code to be friendly to Unix's more permissive file system without losing protection on Windows or in stored cross-platform data.

    // Strict on Windows / Universal, lenient on Unix:
    var opts = PathOptions.PathFormatDependent;
    
    Note

    Use the flag on its own (or with flags other than the unfriendly-name ones) to get this behavior. Combining it with NoUnfriendlyNames makes parsing strict on every format, because those rules are then requested explicitly.

    Choosing the Right Options

    Scenario Recommended options
    App-defined path or user-typed input you'll store PathOptions.NoUnfriendlyNames (default)
    Path returned from an OS file picker that you'll open and discard PathOptions.None
    Path read from a file system enumeration PathOptions.None
    Untrusted user input that must stay inside a known directory PathOptions.NoUnfriendlyNames + PathOptions.NoNavigation
    Cross-platform data that should be strict on Windows but accept everything Unix accepts PathOptions.PathFormatDependent

    Storage and Round-Tripping

    When you store paths, the options used to parse them later must accept everything they accepted originally; otherwise round-trips will fail:

    // At save time:
    var path = FilePath.ParseAbsolute(input, PathOptions.None);
    File.WriteAllText("path.txt", path.PathDisplay);
    
    // At load time (must use the same options):
    var loaded = FilePath.ParseAbsolute(File.ReadAllText("path.txt"), PathOptions.None);
    
    Warning

    If your storage layer trims whitespace (a database column with TRIM, an INI parser, etc.), do not use PathOptions.None; the round-tripped string won't match the original path on the file system. Either constrain inputs to PathOptions.NoUnfriendlyNames or guarantee verbatim storage.

    Checking a Path Against Options

    IPath.IsValidFor tells whether an existing path is valid for a set of options: it returns true exactly when parsing the path's PathDisplay in its own format, as the same kind of path, with those options would succeed. The overload with an out parameter also gives the error message that parsing would give.

    var dir = DirectoryPath.ParseAbsolute(@"C:\data \", PathOptions.None);
    
    dir.IsValidFor(PathOptions.None);                                 // true
    dir.IsValidFor(PathOptions.NoUnfriendlyNames, out string? error); // false, error: "Entry name ends with a space."
    

    The options apply as they do when parsing: NoReservedDeviceNames has no effect on Unix paths, control characters are always invalid in Windows paths, PathFormatDependent adds the unfriendly-name rules for Windows and universal paths only, and AllowEmptyDirectories makes no difference because paths never contain empty directories.

    A path remembers what it is known to be valid for. A parsed path is known to be valid for the options it was parsed with, and paths derived from it (its parent directory, root directory, combined paths and paths with a changed extension) keep what is known about the names they share. Anything else, such as a path from a directory listing, is worked out the first time it is needed, in one pass over the names, and remembered for every later check.

    ValidPath Attribute

    ValidPathAttribute is a DataAnnotations ValidationAttribute that checks a path member with IsValidFor:

    public class StorageOptions
    {
        [ValidPath(PathOptions.NoUnfriendlyNames)]
        public IAbsoluteDirectoryPath? Directory { get; set; }
    }
    
    • A null value is valid; RequiredAttribute is what requires a value.
    • The attribute checks IPath values. A value of any other type, including a string, is invalid and isn't parsed.
    • The default error message is The {0} field is not a valid path. {1}, where {0} is the member's display name and {1} is the reason: the parse error, e.g. The Directory field is not a valid path. Entry name ends with a space., or for a value that isn't a path, its type, e.g. Value of type String is not a path. ErrorMessage or ErrorMessageResourceType and ErrorMessageResourceName replace the message and can use the same placeholders.

    The attribute works with System.ComponentModel.DataAnnotations.Validator, with options validation through ValidateDataAnnotations(), and with the options validation source generator ([OptionsValidator]), which is trim and native AOT compatible.

    Next Steps

    Continue with these related guides:

    • Parsing Paths: where PathOptions is applied.
    • Path Formats: formats interact with options (e.g. PathOptions.PathFormatDependent).
    © Singulink. All rights reserved.