方法一:
Form窗体拖一个FolderBrowserDialog控件 在按钮事件中写入以下代码:
//打开选择文件夹目录
private void btnOpen_Click(object sender, EventArgs e)
{
folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop;
folderBrowserDialog1.Description = "请选择文件夹";
DialogResult d = folderBrowserDialog1.ShowDialog();
if (d == DialogResult.OK)
{
//txtFilesName指的是界面一个文本框获取路径
txtFilesName.Text = folderBrowserDialog1.SelectedPath;
}
else
txtFilesName.Text = "请选择目录!";
}
private void btnEXC_Click(object sender, EventArgs e)
{
Application.Exit();
}
方法二:
新建一个类名字为FolderDialog.cs代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms.Design;
using System.Windows.Forms;
namespace Read
{
public class FolderDialog:FolderNameEditor
{
FolderNameEditor.FolderBrowser fDialog = new System.Windows.Forms.Design.FolderNameEditor.FolderBrowser();
public FolderDialog() { }
public DialogResult DisplayDialog()
{
return DisplayDialog("请选择一个文件夹");
}
public DialogResult DisplayDialog(string description)
{
fDialog.Description = description;
return fDialog.ShowDialog();
}
public string Path
{
get
{
return fDialog.DirectoryPath;
}
}
~FolderDialog()
{
fDialog.Dispose();
}
}
}
在窗体的后台事件调用:
//打开选择文件夹目录
private void btnOpen_Click(object sender, EventArgs e)
{
FolderDialog openFolder = new FolderDialog();
if (openFolder.DisplayDialog() == DialogResult.OK)
{
txtFilesName.Text = openFolder.Path.ToString();
}
else
txtFilesName.Text = "请选择目录!";