C# FolderBrowserDialog
时间: 2025-06-28 09:15:02 浏览: 17
### 如何在C#中使用`FolderBrowserDialog`选择文件夹
#### 使用`FolderBrowserDialog`的基本方法
为了创建并显示文件夹选择对话框,需先创建一个 `FolderBrowserDialog` 类的对象实例。此对象允许开发者配置一些属性以便更好地控制对话框的行为。
```csharp
// 实例化 FolderBrowserDialog 对象
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
```
设置好必要的参数之后,可以调用 `ShowDialog()` 方法来展示该对话框给用户[^1]:
```csharp
// 显示文件夹浏览器对话框,并获取返回的结果
if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string selectedPath = folderBrowserDialog1.SelectedPath;
}
```
这段代码会弹出一个窗口供用户挑选目标文件夹;一旦选择了满意的选项并且点击确认按钮,则可以通过访问 `SelectedPath` 属性得到所选路径字符串[^2]。
#### 完整示例程序
下面给出了一段完整的例子,展示了如何利用上述提到的技术点构建简单的窗体应用,在其中加入了一个按钮控件用于触发打开文件夹选取器的动作以及一个文本框用来呈现最终选定的位置。
```csharp
using System;
using System.Windows.Forms;
public class MainForm : Form {
private Button buttonBrowseFolders;
private TextBox textBoxFolderPath;
public MainForm(){
this.buttonBrowseFolders = new Button();
this.textBoxFolderPath = new TextBox();
// 设置布局和其他初始化工作...
this.buttonBrowseFolders.Click += OnButtonBrowseClick;
}
void OnButtonBrowseClick(object sender, EventArgs e){
using(FolderBrowserDialog dialog = new FolderBrowserDialog()){
if(dialog.ShowDialog()== DialogResult.OK){
textBoxFolderPath.Text=dialog.SelectedPath;
}
}
}
}
static class Program {
[STAThread]
static void Main(){
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
```
以上就是有关于怎样运用 C# 的 `FolderBrowserDialog` 控制台来进行文件夹的选择操作介绍[^3]。
阅读全文
相关推荐


















