1. private void btnOpenFile_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 fileName = oFD.SafeFileName;
    13. string[] stringArray = oFD.SafeFileNames;
    14. foreach (string s in stringArray)
    15. {
    16. fileCbox.Items.Add(s);
    17. }
    18. }
    19. }

    image.png

    1. //string localFilePath, fileNameExt, newFileName, FilePath;
    2. SaveFileDialog sfd = new SaveFileDialog();
    3. //设置文件类型
    4. sfd.Filter = "数据库备份文件(*.bak)|*.bak|数据文件(*.mdf)|*.mdf|日志文件(*.ldf)|*.ldf";
    5. //设置默认文件类型显示顺序
    6. sfd.FilterIndex = 1;
    7. //保存对话框是否记忆上次打开的目录
    8. sfd.RestoreDirectory = true;
    9. //点了保存按钮进入
    10. if (sfd.ShowDialog() == DialogResult.OK)
    11. {
    12. string localFilePath = sfd.FileName.ToString(); //获得文件路径
    13. string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);//获取文件名,不带路径
    14. //获取文件路径,不带文件名
    15. //FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));
    16. //给文件名前加上时间
    17. //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
    18. //在文件名里加字符
    19. //saveFileDialog1.FileName.Insert(1,"dameng");
    20. //System.IO.FileStream fs = (System.IO.FileStream)sfd.OpenFile();//输出文件
    21. ////fs输出带文字或图片的文件,就看需求了
    22. }

    自己写了两个更为通用的方法

    1. /// <summary>
    2. /// 打开文件方法
    3. /// </summary>
    4. /// <param name="isMultiSelect">是否可以多项选择文件</param>
    5. /// <param name="fileType">同一文件类型"Xml文件(*.xml)|*.xml";</param>
    6. /// <param name="filePath">得到打开文件的文件路径</param>
    7. public OpenFileDialog OpenFile(bool isMultiSelect, string fileType)
    8. {
    9. OpenFileDialog o = new OpenFileDialog();
    10. o.InitialDirectory = Application.StartupPath;
    11. o.Title = "打开文件";
    12. o.Multiselect = isMultiSelect;
    13. o.RestoreDirectory = true;
    14. o.Filter = fileType;//"Xml文件(*.xml)|*.xml";
    15. XtraMessageBox.Show(o.Filter);
    16. return o;
    17. }

    这样就会返回一个明确的OpenFileDialog对象,之后如果有其他要求比如多项选择/OpenFileDialog的Filter,都可以通过形参改变
    使用时

    1. OpenFileDialog o = OpenFile(true,"Xml文件(*.xml)|*.xml".Trim());
    2. if (o.ShowDialog() == DialogResult.OK)
    3. {
    4. string[] xmlFile = o.FileNames;
    5. //打开文件之后想要进行的其他操作;
    6. }