Home > Software engineering >  How can I get a list of files and folders in shell folders like shell:Desktop using C#?
How can I get a list of files and folders in shell folders like shell:Desktop using C#?

Time:11-01

I have tried the code below, but it just returns literally ONLY the files and folders in my desktop folder. Whereas when you open shell:Desktop in File Explorer you get the same files PLUS all the drive letters and few other shell folders like "This PC" and Libraries.

DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
foreach (FileInfo fi in di.GetFiles())
    Console.WriteLine(fi.FullName);
foreach (DirectoryInfo subdir in di.GetDirectories())
    Console.WriteLine(subdir.FullName);

CodePudding user response:

DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
        foreach (FileInfo fi in di.GetFiles())
        {
            //All files
            Console.WriteLine(fi.FullName);
        }


        foreach (DirectoryInfo didet in di.GetDirectories())
        {
            //All directories
            Console.WriteLine(didet.FullName);
        }

CodePudding user response:

You need to reference the Shell32 library.

In the Solution Explorer, right-click on your project, choose "Add Reference". Then under "COM", check the "Microsoft Shell" item and click OK.

enter image description here

You can then use the types from that library.

Shell shell = new Shell();
Folder desktop = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDESKTOP);

foreach(ShellFolderItem folderItem in desktop.Items())
{
    Console.WriteLine(folderItem.Type   ": "   folderItem.Name);
}
  • Related