【转载于博客园】cnblogs.com/shuang121/archive/2012/12/01/2797275.html
在winForm中,我们一般会有这样的需求,选择本机的一个图片或者其他文件进去读取或者其他的操作,也可能回选择某一个文件夹下面的所有图片来操作,winForm中为我们提供了两个控件FolderBrowserDialog和OpenFileDialog
【1】FolderBrowserDialog:用来选择一个文件夹,从而读取这个文件夹下面的所有文件
【2】OpenFileDialog: 用来读取单个文件
下面来看看他们具体的用法
首先对于这两个控件我们可以从工具箱里托一个过来,也可以直接用代码创建
《1》先看看FolderBrowserDialog的用法,我们拖一个控件到窗体中,然后实现选择,并将路径返回到文本框中
#region 选择pdf文件目录
private void btnBrowse_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
txtFile.Text = folderBrowserDialog1.SelectedPath;
}
}
《2》OpenFIleDialog的用法也类似
private void button1_Click(object sender, EventArgs e)
{
string Pdfpath = "";
OpenFileDialog op = new OpenFileDialog();
op.Filter = "word Files(*.doc)|*.doc|All Files(*.*)|*.*";
if (op.ShowDialog() == DialogResult.OK)
{
Pdfpath = op.FileName;
}
else
{
Pdfpath = "";
}
textBox1.Text = Pdfpath;
}
【举例1】
private void btnSaveCSPath_Click(object sender, EventArgs e)
{
folderBrowserDialog1.SelectedPath = Application.StartupPath;
folderBrowserDialog1.ShowDialog();
if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
{
txtCSPath.Text = folderBrowserDialog1.SelectedPath;
}
}
private void btnTemplatePath_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.ShowDialog();
if (!string.IsNullOrEmpty(openFileDialog1.FileName))
{
txtTemplatePath.Text = openFileDialog1.FileName;
}
}
【举例2】
private void btnSelectPath_Click( object sender, EventArgs e) |
19 | { |
20 | FolderBrowserDialog path = new FolderBrowserDialog(); |
21 | path.ShowDialog(); |
22 | this .txtPath.Text = path.SelectedPath; |
23 | } |
25 | private void btnSelectFile_Click( object sender, EventArgs e) |
26 | { |
27 | OpenFileDialog file = new OpenFileDialog(); |
28 | file.ShowDialog(); |
29 | this .txtFile.Text = file.SafeFileName; |
30 | } |
判断是否存在文件夹或文件???
if (!Directory.Exists(txtCSPath.Text)) //文件夹
{MessageBox.Show("The path '" + txtCSPath.Text + "' is not existing !", "Saving Settings...", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if ( !File.Exists(txtTemplatePath.Text)) //文件
{
MessageBox.Show("The template '" + txtTemplatePath.Text + "' is not existing !", "Saving Settings...", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}