简体   繁体   中英

OpenFileDialog - How to prevent the default directory from being overwritten?

I'm trying to find a way to reset the initial/default directory after closing an OpenFileDialog. Consider the following example:

using (OpenFileDialog openFile = new OpenFileDialog())
{
    // Example: This opens in the 'Desktop' directory
    // User navigates to 'Documents' directory in the Form before selecting a file
    DialogResult result = openFile.ShowDialog();
    if (result == DialogResult.OK) MessageBox.Show(openFile.FileName);
}

// Somewhere else, this code then runs
using (OpenFileDialog openFile = new OpenFileDialog())
{
    // Problem: This now opens in 'Documents' directory. Not good!
    // How to open using the same default directory (ie: Desktop)?
    DialogResult result = openFile.ShowDialog();
    if (result == DialogResult.OK) MessageBox.Show(openFile.FileName);
}

Just to be clear, 'Desktop' is just an example, I won't actually know the initial directory as it's stored in the registry (if I understand correctly).

I tried using the RestoreDirectory option. This did not seem to have any effect. From what I've read elsewhere it's supposed to reset the Environment.CurrentDirectory back to its original value, which sounds reasonable. However, I don't think OpenFileDialog even uses Environment.CurrentDirectory since the value is never changed, and never matches what OpenFileDialog opens with (unless I manually browse to it).

Is there anything I might be missing here? Does anyone know how to stop overwriting whichever directory variable OpenFileDialog uses as its default?

The default directory is stored in the following registry key on Windows 7.

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32

IIRC, this could be different on other OS's, so you might want to find out the exact directory depending on your OS version.

So what you could do is to grab that value when your application launches, and save it in the memory, and set that to OpenFileDialog.InitialDirectory every time before you open the dialog.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM