Getting the folder name from a full filename path

C#PathFilesystems

C# Problem Overview


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

What objects or methods could I use that would give me a result of folder2?

C# Solutions


Solution 1 - C#

I would probably use something like:

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

The inner call to GetDirectoryName will return the full path, while the outer call to GetFileName() will return the last path component - which will be the folder name.

This approach works whether or not the path actually exists. This approach, does however, rely on the path initially ending in a filename. If it's unknown whether the path ends in a filename or folder name - then it requires that you check the actual path to see if a file/folder exists at the location first. In that case, Dan Dimitru's answer may be more appropriate.

Solution 2 - C#

Try this:

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

Solution 3 - C#

Simple & clean. Only uses System.IO.FileSystem - works like a charm:

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

Solution 4 - C#

DirectoryInfo does the job to strip directory name

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

Solution 5 - C#

I used this code snippet to get the directory for a path when no filename is in the path:

for example "c:\tmp\test\visual";

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

Output:

> visual

Solution 6 - C#

string Folder = Directory.GetParent(path).Name;

Solution 7 - C#

var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();

Solution 8 - C#

It's also important to note that while getting a list of directory names in a loop, the DirectoryInfo class gets initialized once thus allowing only first-time call. In order to bypass this limitation, ensure you use variables within your loop to store any individual directory's name.

For example, this sample code loops through a list of directories within any parent directory while adding each found directory-name inside a List of string type:

[C#]

string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // Notice I've created a DirectoryInfo variable.
    DirectoryInfo dirInfo = new DirectoryInfo(directory);

    // And likewise a name variable for storing the name.
    // If this is not added, only the first directory will
    // be captured in the loop; the rest won't.
    string name = dirInfo.Name;

    // Finally we add the directory name to our defined List.
    directories.Add(name);
}

[VB.NET]

Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()

For Each directory In parentDirectory

    ' Notice I've created a DirectoryInfo variable.
    Dim dirInfo As New DirectoryInfo(directory)

    ' And likewise a name variable for storing the name.
    ' If this is not added, only the first directory will
    ' be captured in the loop; the rest won't.
    Dim name As String = dirInfo.Name

    ' Finally we add the directory name to our defined List.
    directories.Add(name)

Next directory

Solution 9 - C#

Below code helps to get folder name only

public ObservableCollection items = new ObservableCollection();

try { string[] folderPaths = Directory.GetDirectories(stemp); items.Clear(); foreach (string s in folderPaths) { items.Add(new gridItems { foldername = s.Remove(0, s.LastIndexOf('\') + 1), folderpath = s });

            }

        }
        catch (Exception a)
        {
            
        }

public class gridItems { public string foldername { get; set; } public string folderpath { get; set; } }

Solution 10 - C#

This is ugly but avoids allocations:

private static string GetFolderName(string path)
{
    var end = -1;
    for (var i = path.Length; --i >= 0;)
    {
        var ch = path[i];
        if (ch == System.IO.Path.DirectorySeparatorChar ||
            ch == System.IO.Path.AltDirectorySeparatorChar ||
            ch == System.IO.Path.VolumeSeparatorChar)
        {
            if (end > 0)
            {
                return path.Substring(i + 1, end - i - 1);
            }

            end = i;
        }
    }

    if (end > 0)
    {
        return path.Substring(0, end);
    }

    return path;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsh BurlaczenkoView Question on Stackoverflow
Solution 1 - C#LBushkinView Answer on Stackoverflow
Solution 2 - C#WahyuView Answer on Stackoverflow
Solution 3 - C#susieloo_View Answer on Stackoverflow
Solution 4 - C#Abdul SaleemView Answer on Stackoverflow
Solution 5 - C#MarioView Answer on Stackoverflow
Solution 6 - C#larachiwnlView Answer on Stackoverflow
Solution 7 - C#ShawnView Answer on Stackoverflow
Solution 8 - C#Willy KimuraView Answer on Stackoverflow
Solution 9 - C#JoeeView Answer on Stackoverflow
Solution 10 - C#Johan LarssonView Answer on Stackoverflow