如何记住 FolderBrowserDialog 中最后选择的文件夹?

How to remember the last selected folder in FolderBrowserDialog?

我在我的 application.Through 中使用 FolderBrowserDialog 它的构造函数我可以设置 RootPath, SelectedPath。它应该始终以 D:\Export\ 目录作为默认路径打开。如果用户选择任何其他路径,新选择的目录应该反映在 folder.SelectedPath 变量中,如果用户关闭对话框 window 并再次打开它,它应该用上次打开selcted folder(用户选择的文件夹)。它不应打开默认文件夹 (D:\Export)。

public void OpenFolderDialog()
{
FolderBrowserDialog folder = new FolderBrowserDialog(Environment.SpecialFolder.MyComputer, @"D:\Export");
folder.ShowDialog();

    if(!string.IsNullOrEmpty(folderBrowserDialog.SelectedPath) && Directory.Exists(folderBrowserDialog.SelectedPath))
    {
        ExportData(folderBrowserDialog.SelectedPath);
    }
    else
    {
        if (string.IsNullOrEmpty(folderBrowserDialog.SelectedPath))
        {
          log.WarningMsg("FolderBrowserDialog selected path is empty");
         }
         else
         {
           log.WarningMsg("FolderBrowserDialog selected Directory Does not exist");
         }
      }
 }

注意:folderBrowserDialog.SelectedPath 是只读的 属性。我们无法在其中分配任何值。

我们如何记住上次选择的文件夹路径?

您可以在 ShowDialog() 方法 returns:

后立即将 SelectedPath 属性 的值存储在变量中
private string _selectedPath = @"D:\Export\"; // <-- the default value
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    FolderBrowserDialog dialog = new FolderBrowserDialog()
    {
        SelectedPath = _selectedPath
    };
    dialog.ShowDialog();
    _selectedPath = dialog.SelectedPath;
}

如果您想使用 System.Windows.Forms.FolderBrowserDialog,您将不得不将 SelectedPath 值存储在字段或 属性 中,然后将 SelectedPath 设置回在再次调用 ShowDialog 之前在后续调用中使用该值(如 所示)。

但老实说,我不会为此烦恼。对我来说,真正的答案是根本不使用FolderBrowserDialog。从用户的角度来看,该对话框非常不友好。正如 this answer to the question How to use OpenFileDialog to select a folder?, I too recommend using Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog. It's part of a Microsoft NuGet package that can be found here: https://www.nuget.org/packages/Microsoft.WindowsAPICodePack-Shell.

中的建议

此对话框会自动执行您尝试执行的操作:它会记住用户选择的最后一个文件夹,并在用户下次打开该对话框时从该文件夹开始 - 无需额外代码。

用法示例:

var dialog = new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog { IsFolderPicker = true };
if (dialog.ShowDialog() == Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogResult.Ok)
{
    string selected = dialog.FileName;
}