窗体拖拽一个button,代码样例中使用OpenFileDialog对象new一个新实例,等同于在窗体拖拽OpenFileDialog控件,两种方式都可以,实现功能效果是相同的
using System;
using System.Windows.Forms;
namespace WindowsFormsApp11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = "";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// 打开目录定位到当前应用程序目录
openFileDialog1.InitialDirectory = Application.StartupPath;
// 设置OpenFileDialog组件的Filter过滤出多种扩展名的文件
openFileDialog1.Filter = "All files (*.*)|*.*|text files (*.txt;)|*.txt;";
//openFileDialog1.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files(*.*)|*.*";
// 设置默认文件类型显示顺序
openFileDialog1.FilterIndex = 2;
// 是否记忆上次打开的目录
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// 获取文件路径
path = openFileDialog1.FileName;
MessageBox.Show(path);
// 业务操作...
// 业务操作...
// 业务操作...
}
}
}
}