Search code examples
c#.netwinformsfolderbrowserdialog

How can I save and load the last selected folder by user with FolderBrowserDialog?


private void btnStart_Click(object sender, EventArgs e)
{
    System.Windows.Forms.FolderBrowserDialog openFolderDialog = new System.Windows.Forms.FolderBrowserDialog();

    if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        Properties.Settings.Default.LastSelectedFolder = openFolderDialog.SelectedPath.ToString();
        Properties.Settings.Default.Save();
}

The LastSelectedFolder not exist. I tried to go to the project properties to the Settings tab and there i added to the value the LastSelectedFolder.

So now I have: Name Setting Type string Scope user Value LastSelectedFolder

But it's not working still getting the error and also after saving where and how do I load it back when clicking the btnStart?

The LastSelectedFolder is not exist after the Default even after added it to the Settings:

Settings


Solution

  • You have to set the last path as default if you create a new dialog. Therefore you can use also the FolderBrowserDialog.SelectedPath property. Here is your code with the additional line:

    private void btnStart_Click(object sender, EventArgs e)
    {
        System.Windows.Forms.FolderBrowserDialog openFolderDialog = new System.Windows.Forms.FolderBrowserDialog();
        openFolderDialog.SelectedPath = Properties.Settings.Default.LastSelectedFolder;
    
        if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
                Properties.Settings.Default.LastSelectedFolder = openFolderDialog.SelectedPath.ToString();
                Properties.Settings.Default.Save();
        }
    }
    

    In your screenshot you named your setting Setting. Change this one to LastSelectedFolder and clear the default value (last column).

    After that you can compile and run!