Coder Perfect

Obtaining the folder name from the entire path to a filename

Problem

string path = "C:\folder1\folder2\file.txt";

What objects or methods could I use to produce a folder2 result?

Asked by Ash Burlaczenko

Solution #1

I’d most likely say:

string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );

The whole path will be returned by the inner GetDirectoryName() function, while the outer GetFileName() call will return the last path component, which will be the folder name.

This method works regardless of whether or not the path exists. This method does, however, rely on the path terminating in a filename at first. If you are unsure whether the path ends in a filename or a folder name, you must first examine the actual path to see if a file or folder exists at the specified place. Dan Dimitru’s response may be more appropriate in that instance.

Answered by LBushkin

Solution #2

Try this:

string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;

Answered by Wahyu

Solution #3

Simple and uncluttered. System.IO is the only library used. FileSystem – works flawlessly:

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;

Answered by susieloo_

Solution #4

DirectoryInfo performs the task of removing directory names.

string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name;  // System32

Answered by Abdul Saleem

Solution #5

When there is no filename in the path, I use this code snippet to fetch the directory:

for example “c:\tmp\test\visual”;

string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));

Output:

Answered by Mario

Post is based on https://stackoverflow.com/questions/3736462/getting-the-folder-name-from-a-full-filename-path