在文件路径字段上,我想捕获目录路径,例如:
textbox1.Text = directory path
任何人?
如果希望用户选择文件夹,可以使用 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\”
好吧,我正在使用 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";
}
}
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: