C#实现文件夹选择框
文章來源: http://blog.csdn.net/timewolf/article/details/815931
大家都用过C#里的文件打开/保存对话框吧?方便明快且易上手.但是可惜的是,C#居然没提供同样的文件夹选择框,很多人通过P/I invoke使用了系统的一些函数来实现对话框,那是相当地不方便啊~~其实,C#的FolderNameEditor类在某种程度上就实现了文件夹选择框的功能,只不过没有完全包装出来.呵呵,今天就给读者放出一个使用C#自己的类实现的对话框,使用起来就跟OpenFileDialog一样简单易用.
给文件夹选择框类起名叫OpenFolderDialog,类设计如下:
public class OpenFolderDialog : FolderNameEditor, IDisposable
{
FolderNameEditor.FolderBrowser fDialog = new FolderNameEditor.FolderBrowser();
public OpenFolderDialog()
{
}
{
FolderNameEditor.FolderBrowser fDialog = new FolderNameEditor.FolderBrowser();
public OpenFolderDialog()
{
}
public DialogResult ShowDialog()
{
return ShowDialog("Select a folder:");
}
public DialogResult ShowDialog(string description)
{
fDialog.Description = description;
return fDialog.ShowDialog();
}
public string Path
{
get
{
return fDialog.DirectoryPath;
}
}
public void Dispose()
{
fDialog.Dispose();
}
}
使用实例:
private void selectFolderButton_Click(object sender, EventArgs e)
{
using (OpenFolderDialog openFolderDlg = new OpenFolderDialog())
{
if (openFolderDlg.ShowDialog() == DialogResult.OK)
{
this.outFolderTextBox.Text = openFolderDlg.Path;
}
}
}
{
using (OpenFolderDialog openFolderDlg = new OpenFolderDialog())
{
if (openFolderDlg.ShowDialog() == DialogResult.OK)
{
this.outFolderTextBox.Text = openFolderDlg.Path;
}
}
}
下面是对照的OpenFolderDialog使用实例,对照一下,是不是很相似?
private void selectFileButton_Click(object sender, EventArgs e)
{
using (OpenFileDialog openDlg = new OpenFileDialog())
{
openDlg.Filter = @"All text Files(*.txt)|*.txt";
openDlg.Multiselect = false;
openDlg.RestoreDirectory = true;
openDlg.FilterIndex = 1;
if (openDlg.ShowDialog() == DialogResult.OK)
{
this.filePathTextBox.Text = openDlg.FileName;
}
}
}
{
using (OpenFileDialog openDlg = new OpenFileDialog())
{
openDlg.Filter = @"All text Files(*.txt)|*.txt";
openDlg.Multiselect = false;
openDlg.RestoreDirectory = true;
openDlg.FilterIndex = 1;
if (openDlg.ShowDialog() == DialogResult.OK)
{
this.filePathTextBox.Text = openDlg.FileName;
}
}
}