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

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

1
  • 5
    Are you wanting the last folder name so if you had C:\folder1\folder2\folder3\file.txt, you want "folder3"? Commented Sep 17, 2010 at 14:59

12 Answers 12

437

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.

8
  • 207
    Another solution: return new DirectoryInfo(fullPath).Name; Commented Sep 30, 2012 at 13:23
  • 7
    @DavideIcardi Your comment really should be an answer, it's worth it. Commented Aug 10, 2015 at 8:51
  • 5
    This does not work when the path does not include a file (a path to a directory), while @DavideIcardi solution does.
    – Aage
    Commented Feb 10, 2016 at 14:27
  • 2
    An interesting part is that if the path is "C:/folder1/folder2./file.txt" (notice the dot at the end of folder2) the result will be „folder2” and not „folder2.” (which is a perfectly valid folder name) Commented Mar 22, 2018 at 16:10
  • 15
    WARNING: this solution is wrong! For "C:/bin/logs" it returns "bin". Use return new DirectoryInfo(fullPath).Name; instead.
    – Chris W
    Commented Aug 28, 2018 at 14:22
62

Try this:

string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
1
  • 2
    This is the better answer since it actually returns the exact result asked in OP question. Thank you. Commented Nov 8, 2020 at 7:24
40

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

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
1
  • 11
    folder in this case would be file.txt, and not folder2
    – TJR
    Commented Jul 26, 2019 at 20:08
30

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
12

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

1
  • 2
    You can just do Path.GetFileName(dir) and it will return the folder name just fine.
    – jrich523
    Commented Jul 30, 2014 at 16:56
9
string Folder = Directory.GetParent(path).Name;
5
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
1
  • Hard coding the directory separator char () won't work on other platforms. Use Path.DirectorySeparatorChar or at least / instead which works on Unix systems and is the alternative separator in Windows. Commented Sep 20, 2023 at 12:53
2

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
1

I don't know why anyone, did not highlight this solution:

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

Output: folder2

0

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; }
    }
0

An alternative can be to split the path and get the 2nd last element from the path using Index Struct introduced in C# 8.0.

var path = @"C:\folder1\folder2\file.txt";
var folder = path.Split(@"\")[^2]; // 2nd element from the end

Console.WriteLine(folder); // folder2
-2

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;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.