OpenFileDialog InitialDirectory doesn't work

18,950

Solution 1

Do no include filename to InitialDirectory. Path only.

From msdn: On Windows Vista, if InitialDirectory is set to a full file name instead of just a directory path, the initial directory will default either to the application path, or to the directory from which the user last selected a file.

Solution 2

to me those answers didn't help (windows 7).

my path looked like this: "C:/xxxx/yyyyy" after switching to backslash it worked fine, my path now looks like this: "C:\xxxxx\yyyyy"

Solution 3

It may require to set RestoreDirectory

OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = GetDataPath(...);
dialog.RestoreDirectory = true;
dialog.AutoUpgradeEnabled = false;
dialog.Filter = GetFilter(...);
if (dialog.ShowDialog(this) == DialogResult.OK)
{...}

Check this link

Solution 4

I too have tried different "solutions" found in different places, but none of them seem to work as soon as there is an MRU list entry in the registry :/ But here is my own simple workaround…

Instead of setting the dialog's InitialDirectory property, set the FileName property to your path, but combined with the selected Filter, e.g.:

dialog.FileName = Path.Combine(myPath, "*.*");

Solution 5

In my case it was not working because the 'InitialDirectory' did not exist.

    if (!Directory.Exists(InitialDirectory))
        Directory.CreateDirectory(InitialDirectory);
Share:
18,950
Mircea Ispas
Author by

Mircea Ispas

Updated on June 08, 2022

Comments

  • Mircea Ispas
    Mircea Ispas almost 2 years

    I have this code:

    OpenFileDialog dialog = new OpenFileDialog();
    dialog.InitialDirectory = GetDataPath(...);
    dialog.AutoUpgradeEnabled = false;
    dialog.Filter = GetFilter(...);
    if (dialog.ShowDialog(this) == DialogResult.OK)
    {...}
    

    I expect, at every run, to have the dialog in same folder - GetDataPath(...) folder, but it remains in the last selected folder.

    Is this the correct behavior? Do you know how to fix this? If Windows saves last used path in registry do you know how to find it?

    EDIT1:

    With:

    dialog.AutoUpgradeEnabled = true;
    

    is working as expected...

    EDIT2: same problem as here Any known problems with getting SaveFileDialog's InitialDirectory property working in Windows 7?

  • Sandwich
    Sandwich almost 5 years
    This was the answer form me.
  • kuklei
    kuklei over 3 years
    This makes sense and was also my case. No need for other fixes
  • Eric Aya
    Eric Aya over 2 years
  • Eric Aya
    Eric Aya over 2 years
    You can (and should) use the "Edit" button to improve your answer.
  • Rodger
    Rodger over 2 years
    You are going to get downvoted and lose rep if you don't fix the all caps as Eric references. You should definitely do that so that you gain rep from answering the question instead of losing it.