【问题标题】:How to get the list of file in recycle bin by using c# console application如何使用 c# 控制台应用程序获取回收站中的文件列表
【发布时间】:2019-10-25 00:06:47
【问题描述】:

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

我在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();
}

【问题讨论】:

  • 请告诉我们确切的错误以及它发生在哪一行。并告诉我们您正在测试哪个版本的 Windows,以及哪个版本的 .NET Framework。 this answer 似乎至少在 Windows 7 上有效,并且与您的略有不同。你也试过那个吗?
  • Windows 版本很重要,您需要通过在 Main() 方法中添加 [STAThread] 属性来增加它在每个版本上运行良好的几率。

标签: c# .net com recycle-bin shell32


【解决方案1】:

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

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);
            }
        }
    }
}

Here's the helpGetDetailsOf,如果您需要有关文件的任何其他信息

【讨论】:

  • 它的工作!谢谢你的帮助!希望我能完成我的作业。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多