2

I want to keep the last path which is selected. This is the code:

private void testFileButton_Click(object sender, EventArgs e)
{
     fd = new OpenFileDialog();
     fd.FileName = testParameters.testFileFile;
     fd.InitialDirectory = testParameters.testFileDir;

     if (fd.ShowDialog() == DialogResult.OK)
     {                    
         try
         {
            if (fd.SafeFileName != null)
             {
                 testParameters.testFileDir = Path.GetDirectoryName(fd.FileName);
                 testParameters.testFileFile = Path.GetFileName(fd.FileName);
                 testFileLabel.Text = fd.FileName;                 
             }           
          }
          catch (IOException)
          {
              MessageBox.Show("Error: Could not read file");
          }
      }
} 

to be able to keep the last selected path, I tried to add RestorDirectory and index but I did not get any result:

private void testFileButton_Click(object sender, EventArgs e)
{
     fd = new OpenFileDialog();
     fd.FileName = testParameters.testFileFile;
     fd.InitialDirectory = testParameters.testFileDir;
     fd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
     fd.FilterIndex = 2;
     fd.RestoreDirectory = true;

     if(...){
     ...
     }
}

then I tried to use "else" instead:

private void testFileButton_Click(object sender, EventArgs e)
{
    fd = new OpenFileDialog();
    fd.FileName = testParameters.testFileFile;
    fd.InitialDirectory = testParameters.testFileDir;

     if (fd.ShowDialog() == DialogResult.OK)
     {                    
         try
         {
             if (fd.SafeFileName != null)
             {
                 testParameters.testFileDir = Path.GetDirectoryName(fd.FileName);
                 testParameters.testFileFile = Path.GetFileName(fd.FileName);
                 testFileLabel.Text = fd.FileName;                 
             }  
         } 


     }
     catch (IOException)
     {
         MessageBox.Show("Error: Could not read file");
     }


    }
    else
    {
         openFileDialog1.InitialDirectory = @"C:\";
    }
} 

but again without any result..

Does anyone have any idea?

Editing: Last attemp

private void testFileButton_Click(object sender, EventArgs e)
        {
             //http://stackoverflow.com/questions/7793158/obtaining-only-the-filename-when-using-openfiledialog-property-filename
             OpenFileDialog fd = new OpenFileDialog();
             fd.FileName = testParameters.testFileFile;
             Environment.CurrentDirectory = @"C:\" ;

             if (fd.ShowDialog() == DialogResult.OK )
             {                    
                 try
                 {
                    if (fd.SafeFileName != null)
                     {
                         string ffileName = fd.FileName;
                         testParameters.testFileDir = Path.GetDirectoryName(ffileName);
                         testParameters.testFileFile = Path.GetFileName(ffileName);
                         testFileLabel.Text = ffileName;

                     }

                  }
                  catch (IOException)
                  {
                      MessageBox.Show("Error: Could not read file");
                  }
              }
        }   
user3868061
  • 29
  • 1
  • 3
  • If you want to persist data in between calls to `testFileButton_Click` you'll need to store that data somewhere. Do you have a place you can store it? – Philip Pittle Jul 30 '14 at 08:21
  • even for storing a path? No, i do not have! – user3868061 Jul 30 '14 at 08:26
  • You will at least need to keep it in memory. For example, in a `string` data member in the class that contains the method `testFileButton_Click` – Philip Pittle Jul 30 '14 at 08:26
  • But doesn't `testParameters.testFileDir` contain this information? When you set a breakpoint at the beginning of the `testFileButton_Click` method, what does `testParameters.testFileDir` contain? Use the debugger and go through the method step by step. – vgru Jul 30 '14 at 08:27
  • @Groo: I do not know really! – user3868061 Jul 30 '14 at 08:28
  • @user3868061: Are you using Visual Studio? Do you know how to [use the debugger](http://msdn.microsoft.com/en-us/library/y740d9d3.aspx)? Click a line at the beginning of the method, and press F9 to set a breakpoint. Then run the app, and use F10 or F11 to step over each instruction, or step into functions respectively. By hovering your mouse over each variable, you will see its current value. – vgru Jul 30 '14 at 08:34
  • I have tried that several times..when I keep the mouse on the testFileFile it shows the name of the file that I have selected and the testFileDir show the directory correctly. Now, I want to stop debugging and run the code again without selecting the file(testFileFile) again but unfortunately I need to select it again. Since I should choose around 10 files it is difficult to keep going with the debugging the whole project...it is time consuming – user3868061 Jul 30 '14 at 08:41
  • `RestoreDirectory` is irrelevant to your real problem. Its setting controls how the dialog influences the process current/working directory. – David Heffernan Jul 30 '14 at 08:46

5 Answers5

0

The documentation states:

true if the dialog box restores the current directory to its original value if the user changed the directory while searching for files; otherwise, false.

Update: Changing my answer a little, since I think I may have misunderstood your intention:

If I'm not mistaken, your dialog will open to fd.InitialDirectory each time you open it, since that is per definition the default for a new instance of fd. I believe this might be your problem here: You are calling fd = new OpenFileDialog(); each time you are trying to open it.

If you change your code to use the same instance for fd each time (define it in an outer scope, and e.g. access a singleton instance via a Property?), it might remember it's previous directory itself - that is the default behavior (which you can override using the RestoreDirectory property).

Example of getting a singleton instance: This will only instantiate the dialog once, and return the same instance each time you call the property:

Private OpenFileDialog _fd;
private OpenFileDialog SingleFd {
    get { return _fd ?? (_fd = new OpenFileDialog()); }
}


// Now in your method, use:
var singleInstance = SingleFd;
Kjartan
  • 18,591
  • 15
  • 71
  • 96
  • I don't see how the dialog's influence (or otherwise) over the current/working directory is relevant – David Heffernan Jul 30 '14 at 08:44
  • @Kjartan: you are right! the problem is that I am calling OpenFileDialog() each time that I run the code..I will try to fix it even if I do not know how to do it yet.. – user3868061 Jul 30 '14 at 08:54
0
  1. You are not using same variable for file dialog everywhere. Like in if block you are showing file dialog fd, but in else part you are using variable openFileDialog. I couldn't understand why you are doing this, or probably it is a typo. Use same variable at both place if you want to set initial directory to "C:\" if user cancels the dialog.

  2. Instead of creating instance in every call, create an instance once and use it for subsequent calls.

Regarding directory restore, if we don't set initial directory, by default it restores the previous directory, even for the different instances.

Nitin Joshi
  • 1,638
  • 1
  • 14
  • 17
0

OpenFileDialog initially uses the current directory which is a process-wide setting. You have overridden this behavior by setting the InitialDirectory. Just don't do that and it will work.

If you want to persist the last directory used across process restarts, capture Environment.CurrentDirectory and save it. Set it before opening the dialog.

Note, that the current directory is a process-wide setting so that different parts of the app can interfere. Also, all relative paths are interpreted relative to this directory (which is why relative path are usually a bug waiting).

usr
  • 168,620
  • 35
  • 240
  • 369
  • based on your explanation, I changed these two lines but still I do not get what I want: Environment.CurrentDirectory.Equals(fd.FileName); if (fd.ShowDialog() == DialogResult.OK || Environment.CurrentDirectory.Equals(fd.FileName)) – user3868061 Jul 30 '14 at 10:20
  • That doesn't look too good. Equals does not change any value. Any you probably shouldn't compare the CurrentDirectory with a file name. Set the directory to "C:\" and remove InitialDirectory and RestoreDirectory. The dialog should now show C:\. If not, post code. – usr Jul 30 '14 at 10:25
  • @user3868061 Not sure I understand. You said in the question you want to *keep* the last selected path. Now you say you want to *avoid* selecting the last path?! And no matter which one it is: You now can get and set the selected path. Why doesn't that solve your problem? – usr Jul 30 '14 at 10:41
  • Again, how does this not solve your problem? You now can get and set the selected path. Follow up on *all* comments that you receive. – usr Jul 30 '14 at 10:49
0
string path = @"C:\";
        OpenFileDialog fd = new OpenFileDialog();
        fd.FileName = "SelectFolder";
        fd.InitialDirectory =path;
        fd.ValidateNames = false;
        fd.CheckFileExists = false;

        if (fd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if (fd.SafeFileName != null)
                {
                    string txt1 = System.IO.Path.GetFullPath(fd.FileName),
                        txt2 = txt1.Replace("SelectFolder", "").Trim();
                    testFileLabel.Text = txt2.Replace(path, "").Replace(@"\", ""); ;
                }
            }
            catch (IOException)
            {
                MessageBox.Show("Error: Could not read file");
            }
        }
Dwane
  • 1
  • 1
-1

The Solution is to set the InitialDirectory path Blank

openFileDialog.InitialDirectory = ""

openFileDialog.RestoreDirectory = True
RicardoBalda
  • 1,697
  • 6
  • 24
  • 43