Select folder dialog WPF

后端 未结 10 702
暗喜
暗喜 2020-11-28 19:32

I develop a WPF4 application and in my app I need to let the user select a folder where the application will store something (files, generated reports etc.).

My requ

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 19:59

    Windows Presentation Foundation 4.5 Cookbook by Pavel Yosifovich on page 155 in the section on "Using the common dialog boxes" says:

    "What about folder selection (instead of files)? The WPF OpenFileDialog does not support that. One solution is to use Windows Forms' FolderBrowseDialog class. Another good solution is to use the Windows API Code Pack described shortly."

    I downloaded the API Code Pack from Windows® API Code Pack for Microsoft® .NET Framework Windows API Code Pack: Where is it?, then added references to Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll to my WPF 4.5 project.

    Example:

    using Microsoft.WindowsAPICodePack.Dialogs;
    
    var dlg = new CommonOpenFileDialog();
    dlg.Title = "My Title";
    dlg.IsFolderPicker = true;
    dlg.InitialDirectory = currentDirectory;
    
    dlg.AddToMostRecentlyUsedList = false;
    dlg.AllowNonFileSystemItems = false;
    dlg.DefaultDirectory = currentDirectory;
    dlg.EnsureFileExists = true;
    dlg.EnsurePathExists = true;
    dlg.EnsureReadOnly = false;
    dlg.EnsureValidNames = true;
    dlg.Multiselect = false;
    dlg.ShowPlacesList = true;
    
    if (dlg.ShowDialog() == CommonFileDialogResult.Ok) 
    {
      var folder = dlg.FileName;
      // Do something with selected folder string
    }
    

提交回复
热议问题