C#的OpenFileDialog的常用属性设置
1、设置属性
1)设置弹出的指定路径(绝对路径、相等路径)
2)设置标题
3)设置文本格式
2、打开方式1(绝对路径)
2.1) 打开的路径
2.2) 方式1源码
/// <summary>
/// 指定绝对路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//创建对象
OpenFileDialog ofg = new OpenFileDialog();
//判断保存的路径是否存在
if (!Directory.Exists(@"D:\Test\Debug1"))
{
//创建路径
Directory.CreateDirectory(@"D:\Test\Debug1");
}
//设置默认打开路径(绝对路径)
ofg.InitialDirectory = @"D:\Test\Debug1";
//设置打开标题、后缀
ofg.Title = "请选择导入xml文件";
ofg.Filter = "xml文件|*.xml";
string path = "";
if (ofg.ShowDialog() == DialogResult.OK)
{
//得到打开的文件路径(包括文件名)
path = ofg.FileName.ToString();
MessageBox.Show("打开文件路径是:" + path);
}
else if (ofg.ShowDialog() == DialogResult.Cancel)
{
MessageBox.Show("未选择打开文件!");
}
}
2.3)方式1的运行结果
3、打开方式2(相对路径)
3.1) 打开路径2
3.2)方式2源码
/// <summary>
/// 指定相对路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//创建对象
OpenFileDialog ofg = new OpenFileDialog();
//判断保存的路径是否存在
if (!Directory.Exists(Application.StartupPath + @"\Test\Debug1"))
{
//创建路径
Directory.CreateDirectory(Application.StartupPath + @"\Test\Debug1");
}
//设置默认打开路径(项目安装路径+Test\Debug1\)
ofg.InitialDirectory = Application.StartupPath + @"\Test\Debug1";
//设置打开标题、后缀
ofg.Title = "请选择导入xml文件";
ofg.Filter = "xml文件|*.xml";
string path = "";
if (ofg.ShowDialog() == DialogResult.OK)
{
//得到打开的文件路径(包括文件名)
path = ofg.FileName.ToString();
MessageBox.Show("打开文件路径是:" + path);
}
else if (ofg.ShowDialog() == DialogResult.Cancel)
{
MessageBox.Show("未选择打开文件!");
}
}
3.3)方式2结果视图