How do I keep track of the last folder selected by a user?

c#, directory

Solution

There are two places where you can find the last folder accessed by a user:

- `Recent Files and Folders`: It can be found here: `C:\Documents and Settings\USER\Recent`

- `Registry`: In the registry to look here: `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\OpenSaveMRU`

You can use this snippet to find it:

public static string GetLastOpenSaveFile(string extention)
{
    RegistryKey regKey = Registry.CurrentUser;
    string lastUsedFolder = string.Empty;
    regKey = regKey.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU");

    if (string.IsNullOrEmpty(extention))
        extention = "html";

    RegistryKey myKey = regKey.OpenSubKey(extention);

    if (myKey == null && regKey.GetSubKeyNames().Length > 0)
        myKey = regKey.OpenSubKey(regKey.GetSubKeyNames()[regKey.GetSubKeyNames().Length - 2]);

    if (myKey != null)
    {
        string[] names = myKey.GetValueNames();
        if (names != null && names.Length > 0)
        {
            lastUsedFolder = (string)myKey.GetValue(names[names.Length - 2]);
        }
    }

    return lastUsedFolder;
}

OR

In windows XP when you press Save on a `SaveFileDialog` the directory where the file is saved, is set as the new current working directory (the one in `Environment.CurrentDirectory`).

In this way, when you reopen the `FileDialog`, it is opened on the same directory as before.

By setting `FileDialog.RestoreDirectory = true`, when you close the `FileDialog` the original working directory is restored.

In Windows Vista/Seven the behavior is always as `FileDialog.RestoreDirectory = true`.

Problem

I thought using application settings would do the trick but I'm not getting it to work. This is what I have: ``` private void btnBrowse_Click(object sender, EventArgs e) { if (fbFolderBrowser.ShowDialog() == DialogResult.OK) { // I want to open the last folder selected by the user here. } ``` When the user clicks on this button, I want to open the browse window to the last folder he accessed and save it. Next time he clicks on the button, it'll automatically select that folder. I was thinking maybe I could use user variables where I can change at run-time but I'm not getting it to work. Can anyone give me a hand?

Original source