Press "Enter" to skip to content

How to get the folder from a file name in C#

To get the directory of a file name in C#, instantiate a FileInfo object, passing in the file name string to the constructor. Then read the DirectoryName property of the FileInfo object.

You can get the root drive from the FileInfo.Directory.Root.FullName property.

This also works on paths with forward slashes, like Linux systems use.

var fileInfo = new FileInfo(@"e:\a\b\test.txt");
Console.WriteLine(fileInfo.DirectoryName);
Console.WriteLine(fileInfo.Directory.Root.FullName);
var linuxFileInfo = new FileInfo(@"/home/user/Documents/test.txt");
Console.WriteLine(linuxFileInfo.DirectoryName);
Console.WriteLine(linuxFileInfo.Directory.Root.FullName);

Results, from running the code:

e:\a\b
e:\
C:\home\user\Documents
C:\
    Leave a Reply

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

    This site uses Akismet to reduce spam. Learn how your comment data is processed.