When we want to perform operations on path strings containing file or directory path information, the best choice is to call the built-in C# Path Class methods. This class comes under the System.IO namespace and System.Runtime.dll assembly. In this article, we are going to show you the most important operations to simplify path string manipulations.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Is a Path String?

We use a path string to define the file or directory location on a disk, in memory, or on a device.  Each platform determines the path format.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Let’s take a look at some examples for path strings:

  • “c:\\MyDir\\MyFile.txt” in C# (Windows). 
  • “/MyDir/MyFile.txt” in C# (Linux).
  • “\\MyDir\\MySubdir” in C# (Windows). 
  • “/MyDir/MySubdir” in C# (Linux). 

A path can contain absolute or relative location information. Absolute paths fully specify a location. Relative paths use the current location as the starting point for locating a file.

Directory, Path, and Volume Separator Characters

The current platform determines the set of characters for separating the directory, path, volume elements, and the set of characters that we cannot use when specifying paths. Because of these differences, the fields of the Path class as well as the exact behavior of some members of the Path class are platform-dependent.

DirectorySeparatorChar field provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization:

public char DirectorySeparatorChar() 
{ 
     var result = Path.DirectorySeparatorChar;
     Console.WriteLine($"Path.DirectorySeparatorChar: '{result}'");
 
     return result; 
}

In this case, when we run the example the result is:

Path.DirectorySeparatorChar: '\' // Windows system output
Path.DirectorySeparatorChar: '/' // Linux system output

In Windows, there is an alternative Directory separator '/', but in Linux the alternative separator is the same as the DirectorySeparatorChar. We can obtain the alternative separator by using the AltDirectorySeparatorChar field from the Path class: 

public char AltDirectorySeparatorChar() 
{ 
     var result = Path.AltDirectorySeparatorChar;
     Console.WriteLine($"Path.AltDirectorySeparatorChar: '{result}'");

     return result; 
}

The output:

Path.AltDirectorySeparatorChar: '/' // Windows system output
Path.AltDirectorySeparatorChar: '/' // Linux system output

If we use the PathSeparator field, we obtain the platform-specific separator character used to separate path strings in environment variables:

public char PathSeparator() 
{ 
     var result = Path.PathSeparator; 
     Console.WriteLine($"Path.PathSeparator: '{result}'");

     return result; 
}

The path separator also differs from Windows to Linux: 

Path.PathSeparator: ';' //Windows system output 
Path.PathSeparator: ':' //Linux system output

VolumeSeparatorChar provides a platform-specific volume separator character:

public char VolumeSeparatorChar()
{ 
     var result = Path.VolumeSeparatorChar;
     Console.WriteLine($"Path.VolumeSeparatorChar: '{result}'");
 
     return result; 
}

It differs from Windows to Linux as well:

Path.VolumeSeparatorChar: ':' //Windows system output 
Path.VolumeSeparatorChar: '/' //Linux system output

How to Get the Invalid Path Characters?

If we want to get  an array containing the characters that are not allowed in path names, we can use the  GetInvalidPathChars method:

public char[] GetInvalidPathChars()
{
     var result = $"Path.GetInvalidPathChars:";
     var invalidChars = Path.GetInvalidPathChars();       
     Console.WriteLine(result);
            
     foreach (var item in invalidChars)
     {
          Console.Write($"{item} ");
     }            
     Console.WriteLine();
            
     return invalidChars;
}

The GetInvalidPathChars method returns the invalid path characters and we store them in the invalidChars array variable. Then, we iterate over theinvalidChars array to write the content in the console. The output is different if we run the code in a Windows system or a Linux system.

Ends in Directory Separator

The EndsInDirectorySeparator method returns a value that indicates whether the path, specified as a read-only span, ends in a directory separator:

public bool EndsInDirectorySeparator(ReadOnlySpan<Char> filePath)
{
     var result = Path.EndsInDirectorySeparator(filePath);            
     Console.WriteLine($"EndsInDirectorySeparator('{filePath.ToString()}') returns '{result.ToString()}'");
            
     return result;
}

This method receives the filePath parameter of the ReadOnlySpan<Char> type, and returns a bool result variable, confirming whether the given string path ends in a directory separator. It also has another overload accepting the string parameter instead of ReadOnlySpan<char>.

Get or Change Path Extension

The GetExtension method returns the extension (including the “.”) of the specified path string:

public string GetExtension(string fileName)
{
     var extensionString = Path.GetExtension(fileName);            
     Console.WriteLine($"GetExtension('{fileName}') returns '{extensionString}'");
            
     return extensionString;
}

In this case, we declare a path string fileName variable and invoke the GetExtension method which retrieves the extensionString variable. 

If we want to change the path string extension, we can invoke the ChangeExtension method:

public string ChangeExtension(string path, string newExtension)
{            
     var result = Path.ChangeExtension(path, newExtension);            
     Console.WriteLine($"ChangeExtension({path}, '.old') returns '{result}'");
            
     return result;
}

We invoke the ChangeExtension method to change the path string extension from, for example .com, to a new value .old. Additionally, we store the new path in the result variable to print it in the console. 

Combine Strings Into a Path

We can combine two strings into a path by calling the Combine method:

public string Combine(string path1, string path2)
{
     var combination = Path.Combine(path1, path2);            
     Console.WriteLine($"When you combine '{path1}' and '{path2}', the result is: {Environment.NewLine}'{combination}'");

     return combination;
}

Also with the Combine method, we can combine three or four strings or even an array of strings into a path string. You can check our source code for these additional implementations.

Get Directory Name

The GetDirectoryName method returns the directory information for the specified path:

public string GetDirectoryName(string filePath)
{
     var directoryName = Path.GetDirectoryName(filePath);            
     Console.WriteLine($"GetDirectoryName('{filePath}') returns '{directoryName}'");
            
     return directoryName;
}

We call the GetDirectoryname method to extract the directory information from filePath that we accept as a parameter in our GetDirectoryName method.

Get File Name

When we want to return the file name for a given file path string, we can use the GetFileName method:

public ReadOnlySpan<char> GetFileName(ReadOnlySpan<Char> filePath)
{
    ReadOnlySpan<char> fileName = Path.GetFileName(filePath);            
    Console.WriteLine($"GetFileName('{filePath.ToString()}') returns '{fileName.ToString()}'");
            
    return fileName;
}

Get Full Path String

When we call the GetFullPath method, we use the file or directory as a parameter we want to obtain absolute path information for. This method returns the absolute path for the specified path string:

public string GetFullPath(string mydirPath)
{
     var pathResult = Path.GetFullPath(mydirPath);            
     Console.WriteLine($"GetFullPath('{mydirPath}') returns '{pathResult}'");
            
     return pathResult;
}

This method accepts the mydirPath string path parameter and returns the absolute path string, which we store it in the pathResult variable. 

The GetFullPath method has another definition receiving two parameters GetFullPath (string relativepath, string basePath):

public string GetFullPath(string path, string basePath)
{
     var pathResult = Path.GetFullPath(path, basePath);            
     Console.WriteLine($"Fully qualified path:\n {pathResult}");
            
     return pathResult;
}

The first parameter is relativepath to concatenate to basePath. And the second parameter – basePath is the beginning of a fully qualified path.

Get Path Root

The GetPathRoot method returns the root directory information from the path contained in the specified string variable:

public string GetPathRoot(string fullPathString)
{
     var pathRoot = Path.GetPathRoot(fullPathString);            
     Console.WriteLine($"GetPathRoot('{fullPathString}') returns '{pathRoot}'");
            
     return pathRoot;
}

When we pass the fullPathString parameter to the GetPathRoot method, we obtain the root directory stored in the pathRoot string variable.

Concatenate Path Components

In the Path Class, there are several built methods to concatenate path components. All of them share the same name TryJoin and Join, but they receive different parameters. 

If we declare the path components with ReadOnlySpan<Char> variables, we can use the TryJoin method. This method concatenates two, three, or four path components into a single path string:

public void TryJoin(ReadOnlySpan<Char> path1, ReadOnlySpan<Char> path2, Span<Char> destination, out Int32 charsWritten)
{
     if (Path.TryJoin(path1, path2, destination, out charsWritten))
        Console.WriteLine($"Wrote {charsWritten} characters: '{destination.Slice(0, charsWritten).ToString()}'");
     else
        Console.WriteLine("Concatenation operation failed.");
}

Here, we declare two path components path1 and path2 as ReadOnlySpan<Char> parameters. We use both parameters with the TryJoin method to concatenate them into a single path string. The result of the concatenation is stored inside the destination variable. The TryJoin method also has an outcharsWritten parameter. This parameter indicates the number of characters written to the destination. 

Also, it is possible to send two, three, or four path string variables as arguments for obtaining a single path string by using the Join method:

public string Join(string path1, string path2, string path3)
{
     var result = Path.Join(path1, path2, path3);            
     Console.WriteLine($"Path.Join: '{result}'");
            
     return result;
}

In this case, we store the path components in three string variables path1, path2 and path3, and we call the Join method to concatenate them into a single path string. 

Finally, we can concatenate an array of paths into a single path with Join(string[]) method:

public string Join(string[] pathArrayComponents)
{
     var result = Path.Join(pathArrayComponents);            
     Console.WriteLine($"Path.Join: '{result}'");
            
     return result;
}  

Conclusion

In this article, we learned how to work with file and directory path information in C#. We saw how to use different members from the Path class to obtain different pieces of information in both Windows and Linux.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!