3

在文件路径字段上,我想捕获目录路径,例如:

textbox1.Text = directory path

任何人?

4

3 回答 3

10

如果希望用户选择文件夹,可以使用 FolderBrowserDialog 类。

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

如果您只想从完整路径中获取目录,您可以这样做:

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

这会将文本属性设置为“c:\windows\temp\”

于 2008-09-17T07:34:27.753 回答
4

好吧,我正在使用 VS 2008 SP1。这就是我所需要的:

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";
    }
}
于 2008-09-17T08:15:08.887 回答
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

于 2011-06-08T16:03:45.733 回答