Dean Bates
Dean Bates

Reputation: 1957

How can I empty the recycle bin for all users from a Windows service application in c#

I'm looking for a c# snippet which I can insert in a Windows service. The code must empty the recycle bin for all users on the computer.

I have previously tried using SHEmptyRecycleBin (ref http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx) however the code doesn't work when ran from a windows service as the service is running with local system privileges.

Upvotes: 5

Views: 4765

Answers (4)

Bill Tarbell
Bill Tarbell

Reputation: 5234

I'm not sure if it works in a service, but I was able to clear the recycle bin for all users on a windows server by running this in a wpf app as admin.

  DirectoryInfo di = new DirectoryInfo(@"c:\$Recycle.Bin");

  foreach (FileInfo file in di.GetFiles())
    file.Delete();

  foreach (DirectoryInfo dir in di.GetDirectories())
    dir.Delete(true);

The other answers are a bit preachy while presuming to understand the needs of others. In our case we have a server that's used by dozens of people for various bits of QA and dev testing. It's constantly running out of space so we have a cleanup routine we wrote to remove known sources of disposable storage. Everyone is aware of its existence.

Upvotes: 1

Coincoin
Coincoin

Reputation: 28596

First, have you tried running the service on an interactive user account? Maybe SHEmptyRecycleBin requires an interactive user even though it doesn't necessarily display a Window.

Second, I'm not sure it's a good idea to delete other users' stuff but I guess you have a very good reason?

Upvotes: 1

Keith
Keith

Reputation: 155662

Hopefully you can't.

A service running as the local machine should not be clearing my Recycle bin, ever.

You could promote the service to run as an Admin account then it would have the right (and be a security risk), but why do you want to do this? It sounds like the sort of think Viruses try to do.

Upvotes: 4

kokos
kokos

Reputation: 43604

I think doing something like this is against Microsoft recommended practices. What are you trying to do that requires emptying the Recycle Bin from a Windows service?

Upvotes: 2

Related Questions