Initial directory for OpenFileDialog

Cas Nouwens picture Cas Nouwens · Sep 3, 2013 · Viewed 28.6k times · Source

The file dialog has to open the last directory location that was used before it was shut down, but I have no idea how to do this. My colleague only shows me the example of word, when you click "file" it shows the last used files, he told me to use a register or an INI file, which I have never used before.

Here is the code I am using:

string f_sOudeLocatie = @"D:\path\is\classified";

private void btBrowse_Click(object sender, EventArgs e)
{
    OpenFileDialog fdlg = new OpenFileDialog();
    fdlg.Title = "Zoek de CSV file";
    fdlg.InitialDirectory = f_sOudeLocatie;
    fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
    fdlg.FilterIndex = 1;
    fdlg.RestoreDirectory = true;
    if (fdlg.ShowDialog() == DialogResult.OK)
    {
        tbGekozenBestand.Text = fdlg.FileName;
        tbVeranderNaamIn.Text = Path.GetDirectoryName(fdlg.FileName);
        f_sOudeLocatie = Path.GetDirectoryName(fdlg.FileName);
        f_sSourceFileName = fdlg.FileName;
        f_sDestFileName = Path.GetFileName(Path.GetDirectoryName(fdlg.FileName)) + ".csv";
        btOpslaan.Enabled = true;
        tbVeranderNaamIn.ReadOnly = false;
    }
}

Answer

No Idea For Name picture No Idea For Name · Sep 3, 2013

if you'll create the OpenFileDialog outside the button click event it should remember the last folder you've been

string f_sOudeLocatie = @"D:\path\is\classified";
OpenFileDialog fdlg = new OpenFileDialog();

public Form1()
{
    InitializeComponent();
    fdlg.Title = "Zoek de CSV file";
    fdlg.InitialDirectory = f_sOudeLocatie;
    fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
    fdlg.FilterIndex = 1;
    fdlg.RestoreDirectory = true;
}
private void btBrowse_Click(object sender, EventArgs e)
{
    if (fdlg.ShowDialog() == DialogResult.OK)
    {
        fdlg.InitialDirectory = fdlg.FileName.Remove(fdlg.FileName.LastIndexOf("\\"));// THIS LINE IS IMPORTENT

        tbGekozenBestand.Text = fdlg.FileName;
        tbVeranderNaamIn.Text = Path.GetDirectoryName(fdlg.FileName);
        f_sOudeLocatie = Path.GetDirectoryName(fdlg.FileName);
        f_sSourceFileName = fdlg.FileName;
        f_sDestFileName = Path.GetFileName( Path.GetDirectoryName(fdlg.FileName) ) + ".csv";
        btOpslaan.Enabled = true;
        tbVeranderNaamIn.ReadOnly = false;
    }
}