Home > Back-end >  Display first folder name in path
Display first folder name in path

Time:08-11

Hi is there a way to extract the first dir name from the path then display to textbox. like C:\1stFolder\2nFolder\3rdFolder, then i want to display 1stFolder in the textbox

i have a code that only display current selected folder.

textBox5.Text = new DirectoryInfo(FBD.SelectedPath).Name;

CodePudding user response:

DirectoryInfo di = new DirectoryInfo(@"C:\1stFolder\2nFolder\3rdFolder");
while(di.Parent != null && di.Parent.Parent != null)
{
    di = di.Parent;
}
string firstFolderName = di.Name;

CodePudding user response:

** Updated answer based on comment below **

Try this:

void Main()
{
    var dir = @"C:\1stFolder\2nFolder\3rdFolder";
    
    DirectoryInfo info = new System.IO.DirectoryInfo(dir);
    var root = Directory.GetDirectoryRoot(dir);

    while (root != info.Parent.FullName)
    {
        info = System.IO.Directory.GetParent(info.FullName);
    }
    
    Console.WriteLine(info.FullName);
}
  •  Tags:  
  • c#
  • Related