private void btnOpenFile_Click(object sender, EventArgs e ){OpenFileDialog oFD = new OpenFileDialog();oFD.InitialDirectory = Application.StartupPath;oFD.Title = "打开文件";oFD.Multiselect = true;oFD.Filter = "表格文件(*.xls;*.xlsx)|*.xls;*.xlsx|文本文件(*.txt)|*.txt|XML文件(*.xml)|*.xml|所有文件|*.*";oFD.FilterIndex = 2;oFD.RestoreDirectory = true;if(oFD.ShowDialog()==DialogResult.OK){string fileName = oFD.SafeFileName;string[] stringArray = oFD.SafeFileNames;foreach (string s in stringArray){fileCbox.Items.Add(s);}}}

//string localFilePath, fileNameExt, newFileName, FilePath;SaveFileDialog sfd = new SaveFileDialog();//设置文件类型sfd.Filter = "数据库备份文件(*.bak)|*.bak|数据文件(*.mdf)|*.mdf|日志文件(*.ldf)|*.ldf";//设置默认文件类型显示顺序sfd.FilterIndex = 1;//保存对话框是否记忆上次打开的目录sfd.RestoreDirectory = true;//点了保存按钮进入if (sfd.ShowDialog() == DialogResult.OK){string localFilePath = sfd.FileName.ToString(); //获得文件路径string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);//获取文件名,不带路径//获取文件路径,不带文件名//FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));//给文件名前加上时间//newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;//在文件名里加字符//saveFileDialog1.FileName.Insert(1,"dameng");//System.IO.FileStream fs = (System.IO.FileStream)sfd.OpenFile();//输出文件////fs输出带文字或图片的文件,就看需求了}
自己写了两个更为通用的方法
/// <summary>/// 打开文件方法/// </summary>/// <param name="isMultiSelect">是否可以多项选择文件</param>/// <param name="fileType">同一文件类型"Xml文件(*.xml)|*.xml";</param>/// <param name="filePath">得到打开文件的文件路径</param>public OpenFileDialog OpenFile(bool isMultiSelect, string fileType){OpenFileDialog o = new OpenFileDialog();o.InitialDirectory = Application.StartupPath;o.Title = "打开文件";o.Multiselect = isMultiSelect;o.RestoreDirectory = true;o.Filter = fileType;//"Xml文件(*.xml)|*.xml";XtraMessageBox.Show(o.Filter);return o;}
这样就会返回一个明确的OpenFileDialog对象,之后如果有其他要求比如多项选择/OpenFileDialog的Filter,都可以通过形参改变
使用时
OpenFileDialog o = OpenFile(true,"Xml文件(*.xml)|*.xml".Trim());if (o.ShowDialog() == DialogResult.OK){string[] xmlFile = o.FileNames;//打开文件之后想要进行的其他操作;}
