繁体   English   中英

使用 CommonOpenFileDialog 到 select 一个文件夹,但仍显示 Windows 10 文件夹中的文件

[英]Using a CommonOpenFileDialog to select a folder but still show files within the folder in Windows 10

我正在尝试使用CommonOpenFileDialog来允许用户在 select 一个文件夹中,而且还可以在对话框中查看该文件夹内的文件。 目前我的代码只允许用户 select 一个文件夹,但其中的文件是隐藏的,这导致用户认为他们选择了错误的(空)文件夹。

using (var dlg = new CommonOpenFileDialog()
{
    Title = "Select folder to import from",
    AllowNonFileSystemItems = true,
    IsFolderPicker = true,
    EnsurePathExists = true,
    Multiselect = false,
    ShowPlacesList = true
})
{
    if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
    {
        //Do things with the selected folder and the files within it...
    }
}

如何实现针对 Windows 10 的应用程序的目标?

注意:有一个非常相似的问题,标题为“ 我如何只制作 CommonOpenFileDialog select 文件夹,但仍显示文件? ”。 这个问题已经有了很好的答案,但是,没有一个解决方案在 Windows 10 中起作用 由于现有问题已过时(9 年前提出)并且不适用于 Windows 10,因此此问题专门要求提供适用于 Windows 10 设备的解决方案。

我认为 CommonOpenFileDialog 不可能
请参阅: 如何将 IFileDialog 与 FOS_PICKFOLDER 一起使用,同时仍在对话框中显示文件名

唯一的方法是创建您自己的自定义对话框,或者您可以使用带有 P/Invoke 的文件夹对话框(基于 SHBrowseForFolder,如FolderBrowserDialog )。
参见: http://www.pinvoke.net/default.aspx/shell32.shbrowseforfolder

从上面的链接复制 class 并添加选项BIF_BROWSEINCLUDEFILES

public string SelectFolder(string caption, string initialPath, IntPtr parentHandle)
{
    _initialPath = initialPath;
    ...
    bi.ulFlags = BIF_NEWDIALOGSTYLE | BIF_SHAREABLE | BIF_BROWSEINCLUDEFILES;

不幸的是,现在文件仅像FolderBrowserDialog一样显示在对话框中。

是否可以使用类似的东西? 处理FolderChanging事件并读取文件夹名称?

private string SelectFolder()
{
    using (var dlg = new CommonOpenFileDialog()
    {
        Title = "Select folder to import from",
        AllowNonFileSystemItems = true,
        IsFolderPicker = true,
        EnsurePathExists = true,
        Multiselect = false,
        ShowPlacesList = true,
        InitialDirectory = "C:\\" //This must be handled manually
    })
    {
        dlg.FolderChanging += Dlg_FolderChanging;
        if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
        {
            //Do things with the selected folder and the files within it...
            string selectedFolder = dlg.InitialDirectory;
            string dlgFileName = dlg.FileName;
            if (Directory.Exists(dlgFileName))
                selectedFolder = dlgFileName;
            else if (File.Exists(dlgFileName))
                selectedFolder = Path.GetDirectoryName(dlgFileName);
            else if (string.IsNullOrWhiteSpace(lastKnownFolder))
                selectedFolder = lastKnownFolder;

            return selectedFolder;
        }
    }

    return null;
}

private string lastKnownFolder = "";

private void Dlg_FolderChanging(object sender, CommonFileDialogFolderChangeEventArgs e)
{
    lastKnownFolder = e.Folder;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM