Monday, August 8, 2016

Path Class in C# 6.0

Path Class in C# 6.0

The Path class contains methods that can be used to parse a given path. Using these classes is much easier and less error-prone than writing path- and filename-parsing code. If these classes are not used, you could also introduce security holes into your application if the information gathered from manual parsing routines is used in security decisions for your application. There are five main methods used to parse a path: GetPathRoot, GetDirectoryName, GetFileName, GetExtension, and GetFileNameWithoutExtension. Each has a single parameter, path, which represents the path to be parsed [Ref: C# 6.0 Cookbook, 4th Edition By: Stephen Teilhet; Jay Hilyard].

Problem

You need to separate the constituent parts of a path and place them into separate variables.

Solution

Use the static methods of the Path class:

public static void DisplayPathParts(string path)
{
    if (string.IsNullOrWhiteSpace(path))
        throw new ArgumentNullException(nameof(path));

    string root = Path.GetPathRoot(path);
    string dirName = Path.GetDirectoryName(path);
    string fullFileName = Path.GetFileName(path);
    string fileExt = Path.GetExtension(path);
    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(path);
    StringBuilder format = new StringBuilder();
    format.Append($"ParsePath of {path} breaks up into the following pieces:" +
        $"{Environment.NewLine}");
    format.Append($"\tRoot: {root}{Environment.NewLine}");
    format.Append($"\tDirectory Name: {dirName}{Environment.NewLine}");
    format.Append($"\tFull File Name: {fullFileName}{Environment.NewLine}");
    format.Append($"\tFile Extension: {fileExt}{Environment.NewLine}");
    format.Append($"\tFile Name Without Extension: {fileNameWithoutExt}" +
        $"{Environment.NewLine}");
    Console.WriteLine(format.ToString());
}

If the string C:\test\tempfile.txt is passed to this method, the output looks like this:
ParsePath of C:\test\tempfile.txt breaks up into the following pieces:
        Root: C:\
        Directory Name: C:\test
        Full File Name: tempfile.txt
        File Extension: .txt
        File Name Without Extension: tempfile

No comments:

Post a Comment