OpenFileDialog默认路径

using (var openFileDialog1 = new OpenFileDialog()) { openFileDialog1.Reset(); if (!string.IsNullOrEmpty(ExcelFilePath)) { string fileName = Path.GetFileName(ExcelFilePath); string fileExt = Path.GetExtension(ExcelFilePath); //Avoid "you can't open this location using this program file" dialog //if there is a file name in the path strip it ) if (!string.IsNullOrEmpty(fileName)) initialDirectory = Path.GetDirectoryName(ExcelFilePath); //if not let it be else initialDirectory = ExcelFilePath; openFileDialog1.InitialDirectory = initialDirectory; } else openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "Excel files (*.xls or *.xlsx)|*.xls;*.xlsx"; //openFileDialog1.Filter = "xls files (*.xls)|*.xls|xlsx files(*.xlsx)|.xlsx"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = false; openFileDialog1.CheckFileExists = true; openFileDialog1.CheckPathExists = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { var browseSelectionMade = BrowseSelectionMade; if (browseSelectionMade!=null) browseSelectionMade(this, new DataEventArgs(openFileDialog1.FileName)); } } 

无论我是否将RestoreDirectory设置为true,如果我的初始目录设置为不存在的路径,我将始终浏览到LAST使用的目录。 OpenFileDialog保存的最后一个使用目录在哪里? 有没有办法来覆盖这种行为? (例如,我总是想将它设置为C:\,如果初始目录不存在?)

最后使用的目录保存在哪里?

它存储在注册表中。 具体位置取决于Windows版本,对于Win7,它是HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ ComDlg32。 快速查看注册表应该让你相信你不想搞砸。

简单的解决方法是提供有效的路径。 如果您计算的那个无效,则Directory.Exists返回false,然后提供有效的。 与Environment.GetFolderPath()返回的Documents文件夹类似。 再说一次,上次使用的也没有任何问题,用户很容易认识到它恰好接近所需的几率。

您似乎只需要执行以下操作:

 string path; // this is the path that you are checking. if(Directory.Exists(path)) { openFileDialog1.InitialDirectory = path; } else { openFileDialog1.InitialDirectory = @"C:\"; } 

除非我遗漏了一些东西。

我认为没有内置任何东西。 在打开对话框之前检查一下:

 if (!Directory.Exists(initialDirectory)) { openFileDialog1.InitialDirectory = @"C:\"; } 

此外,要设置默认扩展名,您应设置FilterIndex属性而不是DefaultExt。 请参阅: https : //stackoverflow.com/a/6104319/381082

这是一篇关于C#中OpenFileDialog的好文章: http : //www.c-sharpcorner.com/uploadfile/mahesh/openfiledialog-in-C-Sharp/

检查ExcelFilePath是否存在,检查它是否为null或空,但是如果在块之前检查目录是否存在,如果它没有将值重置为空字符串,则应该是黄金。

(是的,你需要先应用你的文件名逻辑等)但是一旦你解析了所有这些,那么确定目录是否退出是微不足道的

 if (!Directory.Exists(excelPath)) { ExcelFilePath = String.Empty; } 

如果您使用存储在某个字符串中的文件名,最好使用Path来剪切文件名(在我的W10上,打开的对话框不会在初始目录中打开,如果我只提供文件名):

  if (!System.IO.Directory.Exists(filename)) { openDlg.InitialDirectory = System.IO.Path.GetDirectoryName(filename); } 

为了将来我

记得这样做:

  try { result = dialog.ShowDialog(Window); } catch { dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); result = dialog.ShowDialog(Window); } 

这有助于用户从位置打开文件,不再存在(例如USB记忆棒,映射网络驱动器) – 如果InitialDirectory无效,ShowDialog会抛出exception。