OpenFileDialog的初始目录在更改到另一个文件夹后不工作

本文关键字:另一个 文件夹 工作 OpenFileDialog | 更新日期: 2023-09-27 18:07:10

我正在用c#开发一个WPF应用程序。在我的应用程序中,我可以打开并保存xml文件,这些文件位于我在app.config中存储的路径中的文件夹中。当我想打开xml文件时,我将OpenFileDialog的InitialDirectory属性设置为配置中的文件夹路径。第一次它工作得很好。但是,如果我同时打开另一个文件夹路径,然后想再次打开xml文件文件夹,我在OpenFileDialog中得到另一个文件夹路径。

我错过了什么?

    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();
    }

OpenFileDialog的初始目录在更改到另一个文件夹后不工作

您可以尝试使用RestoreDirectory属性:

fileDialog。RestoreDirectory = true;

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

属性值类型:System。如果对话框恢复,则为Boolean true如果用户将当前目录改为先前选择的目录在搜索文件时更改目录;否则,假的。的默认值为false。

我找到了。代码是正确的,但我在app.config的设置中犯了一个错误。在路径中我写了"'"而不是"'"。所以路径不正确,VS选择了最后一个路径,而不是InitialDirectory。