dr d b karron
dr d b karron

Reputation: 187

How to c# programmatically or command line open explorer.exe to the "Recycle Bin"

I want a WPF button that will open explorer.exe in Windows 7|8 directly into the "Recycle Bin". This is because my app erases a lot of files, and I want to provide the user with a quick way to restore files. The command line arguments don't work, possibly because the "Recycle Bin" is a virtual directory. I have tried using "$Recycle Bin". Explorer.exe /root, where a is a virtual file fails. Trying to protect the space in Recycle\ Bin does not seem to work as well.

Here is working code from Scott Powell that I tested and am using. Thank you Scott@

    private void ExploreTrashBin ( )
        {
        String str_RecycleBinDir = String.Format(@"C:\$Recycle.Bin\{0}", UserPrincipal.Current.Sid);
        Process . Start ( "explorer.exe" , str_RecycleBinDir );
        }
    private void TrashBin_Button_Click ( object sender , RoutedEventArgs e )
        {
        ExploreTrashBin ( );
        }

Upvotes: 6

Views: 2073

Answers (3)

David
David

Reputation: 16277

It is already implemented in Microsoft.VisualBasic.FileIO.FileSystem class in .Net (so C# natively supports the use of this).

This way, you don't need run shell command : just delete files/folders programmatically as if done interactively with Windows Explorer!

using Microsoft.VisualBasic.FileIO;

FileSystem.DeleteFile(...)
FileSystem.DeleteDirectory(...)

enter image description here

Upvotes: 1

Low Flying Pelican
Low Flying Pelican

Reputation: 6054

You could execute following command in order to achieve this,

start shell:RecycleBinFolder

From your C# code you could use,

System.Diagnostics.Process.Start("explorer.exe", "shell:RecycleBinFolder");

Upvotes: 5

Scott Powell
Scott Powell

Reputation: 215

Recycle Bin is located in a hidden directory named \$Recycle.Bin\%SID%, where %SID% is the SID of the user that performed the deletion.

So based off of this, we can do: Add a .NET reference to System.DirectoryServices.AccountManagement

string str_RecycleBinDir = UserPrincipal.Current.Sid;
Process.Start("explorer.exe","C:\$Recycle.Bin\" + str_RecycleBinDir);

Should be able to now access the proper Recycle Bin directory based off user account that is running. Working in Windows 7 (tested).

Upvotes: 0

Related Questions