[c#] Getting the folder name from a path

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

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

This question is related to c# path filesystems

The answer is


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.


Try this:

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

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

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

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


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

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

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

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

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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to path

Get Path from another app (WhatsApp) How to serve up images in Angular2? How to create multiple output paths in Webpack config Setting the correct PATH for Eclipse How to change the Jupyter start-up folder Setting up enviromental variables in Windows 10 to use java and javac How do I edit $PATH (.bash_profile) on OSX? Can't find SDK folder inside Android studio path, and SDK manager not opening Get the directory from a file path in java (android) Graphviz's executables are not found (Python 3.4)

Examples related to filesystems

Get an image extension from an uploaded file in Laravel Notepad++ cached files location No space left on device How to create a directory using Ansible best way to get folder and file list in Javascript Exploring Docker container's file system Remove directory which is not empty GIT_DISCOVERY_ACROSS_FILESYSTEM not set Trying to create a file in Android: open failed: EROFS (Read-only file system) Node.js check if path is file or directory