Start Directory for OpenFileDialog

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

Here is the code I'm 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; } } 
+6
source share
3 answers

if you create an OpenFileDialog outside the button click event, it should remember the last folder you were in

 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; } } 
+11
source

You need to install

 fdlg.RestoreDirectory = false; 

Cause:

The RestoreDirectory property ensures that the value in Environment.CurrentDirectory is reset before OpenFileDialog closes. If RestoreDirectory is set to false , then Environment.CurrentDirectory will be set to any OpenFileDialog directory for the last time opened. As explained here

+4
source

You can use the registry to store the last directory location. And each time you open the file dialog, get the value from the registry and set it as the default location. When it is closed, return the place to the registry.

This code draft article explains to you what you read and write to the ReadWriteDeleteFromRegistry registry.

If you decide to use an INI file, some search will give you examples of how to read and write from an INI file

+1
source

Source: https://habr.com/ru/post/953029/


All Articles