因为打开和保存继承于FileDialog 同一个,所以做了个通用方法。
//默认打开路径 private string InitialDirectory = "D:\\"; //统一对话框 private bool InitialDialog(FileDialog fileDialog, string title) { fileDialog.InitialDirectory = InitialDirectory;//初始化路径 fileDialog.Filter = "txt files (*.txt,*.*)|*.txt;*.*" ;//过滤选项设置,文本文件,所有文件。 fileDialog.FilterIndex = 1;//当前使用第二个过滤字符串 fileDialog.RestoreDirectory = true;//对话框关闭时恢复原目录 fileDialog.Title = title; if (fileDialog.ShowDialog() == true) { for (int i = 1; i <= fileDialog.FileName.Length; i++) { if (fileDialog.FileName.Substring(fileDialog.FileName.Length -i,1).Equals(@"\")) { //更改默认路径为最近打开路径 InitialDirectory = fileDialog.FileName.Substring(0, fileDialog.FileName.Length - i+1); return true; } } return true; } else { return false; } }
打开文件操作
private void Open(object obj) { OpenFileDialog openFileDialog = new OpenFileDialog();//打开文件对话框 if (InitialDialog(openFileDialog, "Open")) { using (Stream stream = openFileDialog.OpenFile()) { FileName = ((System.IO.FileStream)stream).Name; // 执行相关文件操作
... } } }
保存操作
private void Save(object obj) { SaveFileDialog saveFileDialog = new SaveFileDialog();//打开文件对话框 if (InitialDialog(saveFileDialog, "Save")) { using (Stream stream = saveFileDialog.OpenFile()) { FileName = ((System.IO.FileStream)stream).Name; //执行保存动作 ... MessageBox.Show("保存成功。"); } } }