2

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();
}
CarenRose
  • 1,266
  • 1
  • 12
  • 24
coderSquirrel
  • 41
  • 1
  • 6
  • please tell us the exact error and which line it occurs on. And also tell us which version of windows you are testing on, and which version of the .NET Framework. [this answer](https://stackoverflow.com/a/18071603/5947043) seems to be valid on Windows 7 at least, and is slightly different to yours. Did you try that one as well? – ADyson Jun 10 '19 at 15:13
  • Possible duplicate of [Exception when using Shell32 to get File extended properties](https://stackoverflow.com/questions/31403956/exception-when-using-shell32-to-get-file-extended-properties) – dvo Jun 10 '19 at 15:15
  • 1
    The Windows version matters a lot, you need to increase the odds it works well on every version by putting the [STAThread] attribute on your Main() method. – Hans Passant Jun 10 '19 at 15:25

1 Answers1

2

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

Franck
  • 4,438
  • 1
  • 28
  • 55