Patrick Pirzer
Patrick Pirzer

Reputation: 1759

InitialDirectory of OpenFileDialog not working after change to another folder

I'm working on a WPF application with C# in code-behind. In my app i can open and save XML-files which are in a folder which path i have stored in the app.config. When i want to open an XML-file i set the InitialDirectory property of the OpenFileDialog to the folderpath from the config. The first time it works fine. But in case i opened meanwhile another folderpath and then want to open the XML-file Folder again, i get the other folderpath in my OpenFileDialog.

What have i missed?

    private void openXMLFile(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
        fileDialog.InitialDirectory = System.Configuration.ConfigurationManager.AppSettings["SerializedXmlFolderPath"].ToString();
        fileDialog.Filter = "xml files (*.xml)|*.xml";
        fileDialog.FilterIndex = 1;

        if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
            string fileNameWithType = fileDialog.SafeFileName.Trim();
            if (fileNameWithType == null || fileNameWithType.Length < 5 || !fileNameWithType.EndsWith(".xml")) {
                MessageBox.Show("This is not a file name, that can be used!");
                return;
            }
            formularsCommonName = fileNameWithType.Substring(0, fileNameWithType.Length - 4);
            directory = Path.GetDirectoryName(fileDialog.FileName) + Path.DirectorySeparatorChar;
            string fileName = directory + formularsCommonName + ".xml";
            loadXMLFile(fileName);
        }
        fileDialog.Dispose();
    }

Upvotes: 0

Views: 2504

Answers (2)

Patrick Pirzer
Patrick Pirzer

Reputation: 1759

I found it. The code is correct, but i made a mistake in the Settings of my app.config. In the paths i wrote "\" instead of "\". So the paths were not correct and VS took the last path instead of InitialDirectory.

Upvotes: 0

Quentin Roger
Quentin Roger

Reputation: 6538

You can try to play with the RestoreDirectory property :

fileDialog.RestoreDirectory= true;

https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.restoredirectory(v=vs.110).aspx

Property Value Type: System.Boolean true if the dialog box restores the current directory to the previously selected directory if the user changed the directory while searching for files; otherwise, false. The default value is false.

Upvotes: 1

Related Questions