OpenFileDialog默认路径

Eu *_*upu 20 c#

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<string>(openFileDialog1.FileName));
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

Jet*_*tti 37

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

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

除非我遗漏了一些东西.


Han*_*ant 17

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

它存储在注册表中.具体位置取决于Windows版本,对于Win7,它是HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32.就让我们来看看与注册表编辑器应该说服你,你希望与那些乱七八糟.

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


Du *_* D. 5

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

if (!Directory.Exists(initialDirectory))
{
    openFileDialog1.InitialDirectory = @"C:\";
}
Run Code Online (Sandbox Code Playgroud)