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));
}
}无论我是否将RestoreDirectory设置为true,如果我的初始目录设置为不存在的路径,我将始终浏览到上次使用的目录。OpenFileDialog保存的最后一次使用的目录在哪里?有什么方法可以覆盖这个行为吗?(例如,如果初始目录不存在,我总是想将其设置为C:\?)
发布于 2012-04-03 01:08:46
上一次使用的目录保存在哪里?
它存储在注册表中。具体位置取决于Windows版本,对于Win7,它是HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32.快速浏览一下regedit应该会让你相信,你不想把它搞乱。
简单的解决方法是提供有效路径。如果您计算的值无效,Directory.Exists将返回false,然后提供一个有效的值。类似于Environment.GetFolderPath()返回的Documents文件夹。话又说回来,上一次使用的那个也没有什么问题,用户会很容易地识别它,因为它恰好接近所需的那个。
发布于 2012-04-03 00:56:00
看起来你只需要做以下几件事:
string path; // this is the path that you are checking.
if(Directory.Exists(path)) {
openFileDialog1.InitialDirectory = path;
} else {
openFileDialog1.InitialDirectory = @"C:\";
} 除非我漏掉了什么。
发布于 2012-04-03 00:57:33
我不认为有什么是内置的。只需在打开对话框之前进行检查:
if (!Directory.Exists(initialDirectory))
{
openFileDialog1.InitialDirectory = @"C:\";
}https://stackoverflow.com/questions/9980262
复制相似问题