3

On a file path field, I want to capture the directory path like:

textbox1.Text = directory path

Anyone?

MPelletier
  • 16,256
  • 15
  • 86
  • 137
MarlonRibunal
  • 4,009
  • 3
  • 31
  • 37

3 Answers3

10

There is a FolderBrowserDialog class that you can use if you want the user to select a folder.

http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx

DialogResult result = folderBrowserDialog1.ShowDialog();
if (result.Equals(get_DialogResult().OK)) {
    textbox1.Text = folderBrowserDialog1.get_SelectedPath();
}

If all you want is to get the direcotory from a full path, you can do this:

textbox1.Text = Path.GetDirectoryName(@"c:\windows\temp\myfile.txt");

This will set the Text-property to "c:\windows\temp\"

Espo
  • 41,399
  • 21
  • 132
  • 159
  • 1
    Oh man, I thought this was a good solution until I realized which dialog this shows - I HATE that dialog! [http://i.imgur.com/2uGPK.png](http://i.imgur.com/2uGPK.png) – Pat Jun 07 '11 at 21:36
4

Well I am using VS 2008 SP1. This all I need:

private void button1_Click(object sender, EventArgs e)
{
    FolderBrowserDialog profilePath = new FolderBrowserDialog();

    if (profilePath.ShowDialog() == DialogResult.OK)        
    {
        profilePathTextBox.Text = profilePath.SelectedPath;
    }
    else
    {
        profilePathTextBox.Text = "Please Specify The Profile Path";
    }
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
MarlonRibunal
  • 4,009
  • 3
  • 31
  • 37
1

If you don't want a terrible, non-user friendly dialog*, try Ookii.Dialogs or see other answers to How do you configure an OpenFileDialog to select folders?. The only downside I see to Ookii is that it requires .NET 4 Full, not just Client Profile. But the source is included in the download, so I'm going to work on that. Too bad the license isn't LGPL or similar...

See also: WinForms message box with textual buttons

*This is what FolderBrowserDialog looks like:

Ugly, unfriendly folder browser dialog

Community
  • 1
  • 1
Pat
  • 16,515
  • 15
  • 95
  • 114