Question

I have a OpenFileDialog which should open up a specific path say %ProgramData% when 'Browse' clicked for the first time the user uses the application. And for all successive terms, it should open up the last used folder.

I tried:

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = "C:\ProgramData";
        ofd.RestoreDirectory = true;
        ofd.FileName = "";
        DialogResult dr = ofd.ShowDialog();

The problem here is, it opens up "C:\ProgramData" every time, even if I change path while looking for the required file. Is there a specific property that I should set or do I have to programmatically keep track of the usage of the OpenFileDialog and set path accordingly?

Was it helpful?

Solution

Try this:

you are resetting intialdirectory to C:\ProgramData on button click

public partial class Form1 : Form
    {
           OpenFileDialog ofd = new OpenFileDialog();

        public Form1()
        {
            InitializeComponent();
            ofd.InitialDirectory = "C:\\ProgramData";
        }    
        private void button1_Click(object sender, EventArgs e)
        {                     
          DialogResult dr = ofd.ShowDialog();
          ofd.InitialDirectory = null;   
        }    
    }

OTHER TIPS

Do something like this:

// save your current directory  
string currentDirectory = Environment.CurrentDirectory;  

// create an OpenFileDialog and set RestoreCurrentDirectory to false.   
OpenFileDialog ofd = new OpenFileDialog();  
ofd.RestoreCurrentDirectory = false;  
ofd.ShowDialog();  

// save the selected directory locally.   
string selectedDirectory = Environment.CurrentDirectory;  // OpenFileDialog changed this value.   
Environment.CurrentDirectory = currentDirectory; // reset the property with the first value.   

// next time you open an OpenFileDialog, set the InitialDirectory property  
OpenFileDialog ofd2 = new OpenFileDialog();  
ofd.InitialDirectory = selectedDirectory; // set the InitialDirectory to what it was last time an OpenFileDialog was opened.   
ofd.ShowDialog(); 

RestoreDirectory property makes sure that the value in Environment.CurrentDirectory will be reset before the OpenFileDialog closes. If RestoreDirectory is set to false, then Environment.CurrentDirectory will be set to whatever directory the OpenFileDialog was last open to.

I think you are reading the RestoreDirectory property wrong. It, in fact, restores the directory to the default after the dialog is closed. Just the opposite to what you want to do.

Also check out: OpenFileDialog RestoreDirectory as no effect if Multiselect is set to true

Simply,

Set FileDialog.RestoreDirectory Property true. When reopenning the file dialog box, it locates the last directory.

Example :

ofd . RestoreDirectory = true;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top