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

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类型。

复制代码

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 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章