<完整读取文件程序>

    1. private void button1_Click(object sender, EventArgs e)
    2. {
    3. OpenFileDialog oFD = new OpenFileDialog();
    4. oFD.InitialDirectory = Application.StartupPath;
    5. oFD.Title = "打开文件";
    6. oFD.Multiselect = true;
    7. oFD.Filter = "表格文件(*.xls;*.xlsx)|*.xls;*.xlsx|文本文件(*.txt)|*.txt|XML文件(*.xml)|*.xml|所有文件|*.*";
    8. oFD.FilterIndex = 2;
    9. oFD.RestoreDirectory = true;
    10. if(oFD.ShowDialog()==DialogResult.OK)
    11. {
    12. string filePath = oFD.FileName;
    13. string fileName = oFD.SafeFileName;
    14. }
    15. }

    实例:Form form=new Form();
    //OpenFileDialog构造函数
    OpenFileDialog dialog = new OpenFileDialog
    {
    Multiselect = true,//该值确定是否可以选择多个文件
    Title = “请选择文件夹”,
    Filter = “文件(.xml,.txt)|.xml;.txt”
    };
    方式1:form.Text=”打开文件:” + dialog.SafeFileName;
    方式2:form.Text=”打开文件:” + System.IO.Path.GetFileName(dialog.FileName);
    方式3: string s = dialog.FileName;
    s = s.Substring(s.LastIndexOf(‘\‘) + 1, s.LastIndexOf(‘.’) - s.LastIndexOf(‘\‘) - 1);
    form.Text = “打开文件:” + s;

    PS:
    OpenFileDialog
    OpenFileDialog.SafeFileName 获取对话框中所选文件的文件名和扩展名字,文件名不包含路径
    string string.Substring(int StartIndex,int length)从指定字符位置开始,长度为length,得到字符串类型
    int string.LastIndexOf(char value)