Search code examples
c#.netcomrecycle-binshell32

How to get the list of file in recycle bin by using c# console application


I am working on homework to get the file count of the recycle bin by using shell32.dll. However, I am struggling to display the list of the files in the recycle bin and keep getting a System.InvalidCastException error when I try to use the shell.

I have browsed for quite a few solutions on Stack Overflow, and most of them used shell32.dll to get the files list of the recycle bin.

The latest code I've tried is as below:

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

Solution

  • This error is most likely due to the fact you are missing the STAThread on the method. Thes following example is an old test which does actually the same thing you are trying to do. If the error is on the getting the actual name then i noticed yours is different then how i used to do it. I am requesting the folder to give me specific details about it's file.

    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 help on the GetDetailsOf if you need any other information on the file