您的位置:首页 > 编程语言 > C#

C#中OpenFileDialog获取文件名和文件路径的常用方法.

2016-12-11 14:58 851 查看
System.IO.Path.GetFullPath(openFileDialog1.FileName);                             //绝对路径


System.IO.Path.GetExtension(openFileDialog1.FileName);                          //文件扩展名

System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);//文件名没有扩展名

System.IO.Path.GetFileName(openFileDialog1.FileName);                          //得到文件

System.IO.Path.GetDirectoryName(openFileDialog1.FileName);                  //得到路径


以上函数的返回值都是是string类型。

下面附上选择本地文件的按钮的监听事件的C#代码:


[csharp] view
plain copy

using System;  

using System.Collections.Generic;  

using System.ComponentModel;  

using System.Data;  

using System.Drawing;  

using System.Linq;  

using System.Text;  

using System.Windows.Forms;  

  

namespace browseFile  

{  

    public partial class Form1 : Form  

    {  

        public Form1()  

        {  

            InitializeComponent();  

        }  

  

        private void button1_Click(object sender, EventArgs e)  

        {  

            OpenFileDialog fdlg = new OpenFileDialog();  

            fdlg.Title = "C# Corner Open File Dialog";  

            fdlg.InitialDirectory = @"c:\";   //@是取消转义字符的意思  

            fdlg.Filter = "All files(*.*)|*.*|All files(*.*)|*.* ";  

            /* 

             * FilterIndex 属性用于选择了何种文件类型,缺省设置为0,系统取Filter属性设置第一项 

             * ,相当于FilterIndex 属性设置为1.如果你编了3个文件类型,当FilterIndex =2时是指第2个. 

             */  

            fdlg.FilterIndex = 2;  

            /* 

             *如果值为false,那么下一次选择文件的初始目录是上一次你选择的那个目录, 

             *不固定;如果值为true,每次打开这个对话框初始目录不随你的选择而改变,是固定的   

             */  

            fdlg.RestoreDirectory = true;  

            if(fdlg.ShowDialog() == DialogResult.OK)  

            {  

                textBox1.Text = System.IO.Path.GetFileNameWithoutExtension(fdlg.FileName);  

          

            }  

  

        }  

    }  

}  

参考 http://blog.sina.com.cn/s/blog_7511914e0101cbjn.html   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: