首页 > 解决方案 > 如何使用 c# 控制台应用程序获取回收站中的文件列表

问题描述

我正在做作业以使用 shell32.dll 获取回收站的文件数。但是,我正在努力显示回收站中的文件列表,并在System.InvalidCastException尝试使用 shell 时不断出错。

我在 Stack Overflow 上浏览过不少解决方案,大部分都是使用 shell32.dll 来获取回收站的文件列表。

我尝试过的最新代码如下:

public static void Main(string[] args)
{
    Shell shell = new Shell();
    Folder folder = shell.NameSpace(0x000a);

    foreach (FolderItem2 item in folder.Items())
        Console.WriteLine("FileName:{0}", item.Name);

    Marshal.FinalReleaseComObject(shell);
    Console.ReadLine();
}

标签: c#.netcomrecycle-binshell32

解决方案


此错误很可能是由于您缺少STAThreadon 方法。以下示例是一个旧测试,它实际上与您尝试做的事情相同。如果错误在于获取实际名称,那么我注意到您的名称与我过去的做法不同。我要求该文件夹向我提供有关其文件的具体详细信息。

using Shell32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApplication1101
{
    class Program
    {
        [STAThread()]
        static void Main(string[] args)
        {
            // create shell
            var shell = new Shell();

            // get recycler folder
            var recyclerFolder = shell.NameSpace(10);

            // for each files
            for (int i = 0; i < recyclerFolder.Items().Count; i++)
            {
                // get the folder item
                var folderItems = recyclerFolder.Items().Item(i);

                // get file name
                var filename = recyclerFolder.GetDetailsOf(folderItems, 0);

                // write file path to console
                Console.WriteLine(filename);
            }
        }
    }
}

如果您需要有关GetDetailsOf文件的任何其他信息,这里是帮助


推荐阅读