1

Hi how can I display selected folder name in textbox. I have 3 Folder. It display the 2 folders in the textbox but the other one it won't display.

For example:

C:\EmpRecord\Details\Name\MiddleName\Lastname

The 2 folder name display without a problem.

For the Middlename here's the code:

middleName.Text = Path.GetFileName(Path.GetDirectoryName(folderBrowserDialog1.SelectedPath));

Lastname:

lastName.Text = new DirectoryInfo(folderBrowserDialog1.SelectedPath).Name;

For the Name it doesn't display in the textbox. How can I display it in textbox?

  • Does [this](https://stackoverflow.com/questions/401304/how-does-one-extract-each-folder-name-from-a-path) answer your incomprehensible question ? – Orace Nov 24 '22 at 18:09

3 Answers3

0

You just need to call GetFileName and GetDirectoryName multiple times, e.g.

var folderPath = @"C:\EmpRecord\Details\Name\MiddleName\Lastname";

Console.WriteLine(Path.GetFileName(folderPath);

folderPath = Path.GetDirectoryName(folderPath);

Console.WriteLine(Path.GetFileName(folderPath);

folderPath = Path.GetDirectoryName(folderPath);

Console.WriteLine(Path.GetFileName(folderPath);

That will display the following:

Lastname
MiddleName
Name
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • How to implement for textbox? – Tintin Santos Nov 23 '22 at 01:11
  • @TintinSantos, you're seriously asking me how to display a `string` in a `TextBox`? Apart from that, you're already displaying the result of `Path.GetFileName` in a `TextBox` in your own code so why do I need to show you how to do something that you're already doing? – jmcilhinney Nov 23 '22 at 01:22
0

Try this:

Name.Text = folderBrowserDialog1.SelectedPath.Substring(folderBrowserDialog1.SelectedPath.LastIndexOf(@"\") + 1).Substring(4));
Jonathan Barraone
  • 489
  • 1
  • 3
  • 20
0

Another one using the Uri class:

Uri uri = new Uri(folderBrowserDialog1.SelectedPath);            
if (uri.Segments.Length >= 3)
{
    lastName.Text = uri.Segments[uri.Segments.Length - 1].Trim('/');
    middleName.Text = uri.Segments[uri.Segments.Length - 2].Trim('/');
    firstName.Text = uri.Segments[uri.Segments.Length - 3].Trim('/');
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40