How To Work With Directory Path In C#

The C# Path lesson demonstrates how to use the file and directory path data in C#. The operations are performed in a cross-platform manner.

Path.GetDirectoryName

The Path.GetDirectoryName gives back directory details for a path that is supplied and is represented by a character span.

var path = "/home/test/text.txt";
var dirName = Path.GetDirectoryName(path);

Console.WriteLine(dirName);

The example outputs the directory name of the specified path.

/home/test

Path.GetPathRoot

The Path.GetPathRoot function retrieves information about the root directory’s path from the character span that is supplied.

var path = "/home/test/tmp/";
var root = Path.GetPathRoot(path);

Console.WriteLine(root);

The example outputs the root path of the specified path.

/

Path.GetFullPath

The Path.GetFullPath returns the absolute path for the specified path string.

var path = "abc.txt";

var fullPath = Path.GetFullPath(path);

Console.WriteLine(fullPath);

The example prints the full path of the current working directory.

/home/test/abc.txt

Path filename and extension

The Path.GetExtension retrieves the supplied path string’s extension (complete with the period).The Path.GetFileName delivers a file path represented by a read-only character span’s file name and extension.

The Path.GetFileNameWithoutExtension retrieves a file path represented by a read-only character span’s file name without the extension.

var path = "/home/test/text.txt";

var fileExt = Path.GetExtension(path);
Console.WriteLine(fileExt);

var fileName = Path.GetFileName(path);
Console.WriteLine(fileName);

var fileNameWithoutExt = Path.GetFileNameWithoutExtension(path);
Console.WriteLine(fileNameWithoutExt);

The example prints the extension, the file name, and the file name without the extension of the specified path.

.txt
text.txt
text

Path.Combine

The Path.Combine combines strings into a path.

var fullPath1 = Path.Combine("/home", "test", "abc.txt");
Console.WriteLine(fullPath1);

var fullPath2 = Path.Combine("/home/test/", "/home/test/temp.txt");
Console.WriteLine(fullPath2);

The example joins separate strings to create a single string that stands in for a file path.

home/test/abc.txt
home/test/temp.txt

Path.GetRandomFileName

The Path.GetRandomFileName returns a random directory or file name.

var randFileName = Path.GetRandomFileName();
Console.WriteLine(randFileName);

Console.WriteLine(Path.GetTempPath());

The example prints an example of a randomly generated file name.

dffxinfj.zrh

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories