You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#获取桌面选中文件路径问题:现有代码返回空列表

解决C#获取桌面选中文件路径的问题

你的代码只能捕获资源管理器窗口的选中项,桌面是独立的Shell视图,不在exShell.Windows()返回的集合中,所以需要单独处理桌面的选中内容。

以下是修正后的完整代码:

using System.Collections.Generic;
using Shell32; // 需要添加引用:COM组件「Microsoft Shell Controls And Automation」

public List<string> GetAllSelectedFilesAndFolders()
{
    List<string> selectedItems = new List<string>();
    Shell shell = new Shell();

    // 1. 获取资源管理器窗口中的选中项
    foreach (ShellBrowserWindow window in (IShellWindows)shell.Windows())
    {
        if (window.Document is IShellFolderViewDual folderViewDual)
        {
            foreach (FolderItem item in folderViewDual.SelectedItems)
            {
                selectedItems.Add(item.Path);
            }
        }
        else if (window.Document is ShellFolderView folderView)
        {
            foreach (FolderItem item in folderView.SelectedItems)
            {
                selectedItems.Add(item.Path);
            }
        }
    }

    // 2. 获取桌面的选中项
    Folder desktopFolder = shell.NameSpace(0x0000); // 0x0000 代表桌面文件夹
    if (desktopFolder != null && desktopFolder.Self.GetFolder is Folder2 desktopFolder2)
    {
        ShellFolderView desktopView = desktopFolder2.View as ShellFolderView;
        if (desktopView != null)
        {
            foreach (FolderItem item in desktopView.SelectedItems)
            {
                selectedItems.Add(item.Path);
            }
        }
    }

    return selectedItems;
}

关键说明:

  • 桌面通过shell.NameSpace(0x0000)获取,这个常量对应桌面的PIDL标识
  • 需要将桌面文件夹转换为Folder2类型才能访问其View属性,进而获取选中项
  • 确保项目已添加「Microsoft Shell Controls And Automation」COM引用(在解决方案资源管理器的「引用」→「添加引用」→「COM」标签下查找)

内容的提问来源于stack exchange,提问作者Snuden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 09:15:31