C#里面有选择文件的对话框控件,却没有选择文件夹的对话框控件,不少人为了选择一个文件夹只好自己用TreeView类来处理,其实在C#里面完全不用那么麻烦,我们可以用C#的FolderNameEditor类的子类FolderBrowser类来实现获取浏览文件夹对话框的功能。
下面来看看具体是怎么实现的。
首先新建一个winform的项目
新建一个FolderDialog类,此类从FolderNameEditor类继承,在此类中新建一个FolderBrowser类的实例。DisplayDialog(stringdescription)函数用于设置实例fDialog的属性,并且显示浏览文件夹对话框。为了取得文件夹的路径,设置一个Path属性,返回选取文件夹的路径。
因为FolderNameEditor是在System.Windows.Forms.Design命名空间下的,此命名空间位于动态链接库system.design.dll,所以我们要先在解决方案中添加新的引用(reference)System.Design。然后在代码中添加:
using System.Windows.Forms.Design;
1. public class FolderDialog : FolderNameEditor
2. {
3. FolderNameEditor.FolderBrowser fDialog =newSystem.Windows.Forms.Design.FolderNameEditor.FolderBrowser();
4. public FolderDialog()
5. {
6. }
7. public DialogResult DisplayDialog()
8. { return DisplayDialog("请选择一个文件夹"); }
9. public DialogResult DisplayDialog(stringdescription)
10. {
11. fDialog.Description = description;
12. return fDialog.ShowDialog();
13. }
14. public string Path { get { return fDialog.DirectoryPath; } }
15. ~FolderDialog() { fDialog.Dispose(); }
16. }
public class FolderDialog : FolderNameEditor
{
FolderNameEditor.FolderBrowser fDialog = newSystem.Windows.Forms.Design.FolderNameEditor.FolderBrowser();
public FolderDialog()
{
}
public DialogResultDisplayDialog()
{ returnDisplayDialog("请选择一个文件夹"); }
public DialogResultDisplayDialog(string description)
{
fDialog.Description =description;
returnfDialog.ShowDialog();
}
public string Path { get {return fDialog.DirectoryPath; } }
~FolderDialog() {fDialog.Dispose(); }
}
//在winform窗体里写以下代码,可以看看运行效果。
1. private void Form1_Load(object sender,System.EventArgs e)
2. {
3. FolderDialog aa=new FolderDialog ();
4. aa.DisplayDialog ();
5. MessageBox.Show (aa.Path);
6. }
private void Form1_Load(object sender, System.EventArgs e)
{
FolderDialog aa=new FolderDialog();
aa.DisplayDialog ();
MessageBox.Show (aa.Path);
}
示例代码:
///
/// 选择保存htm文件的文件夹
///
///
///
private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
folderBrowserDialog1.Description = "请选择保存htm文件的文件夹";
//folderBrowserDialog1.ShowNewFolderButton = true;
//folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string folderName = folderBrowserDialog1.SelectedPath;
if (folderName != "")
{
textBox1.Text = folderName;
SaveHtmPath_EXCEL = textBox1.Text;
}
}
}