簡體   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