Click here to Skip to main content
13,151,998 members (40,538 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.7K views
7 bookmarked
Posted 24 Sep 2012

How to Delete a File or Folder to Recyclebin

, 24 Sep 2012
Rate this:
Please Sign up or sign in to vote.
How to delete a file or folder to Recyclebin

If we delete file or folder using C# code, it will be deleted from the system permanently. Yesterday, I was searching for a solution which helps me to delete file to recycle bin. There is no direct API* available in .NET which helps me to achieve this. Later, I found an option using SHFileOperation function. And here is the implementation, which helps to delete file or folder to Recyclebin.

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
{
    public IntPtr hwnd;
    [MarshalAs(UnmanagedType.U4)]
    public int wFunc;
    public string pFrom;
    public string pTo;
    public short fFlags;
    [MarshalAs(UnmanagedType.Bool)]
    public bool fAnyOperationsAborted;
    public IntPtr hNameMappings;
    public string lpszProgressTitle;
}

[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);

public const int FO_DELETE = 3;
public const int FOF_ALLOWUNDO = 0x40;
public const int FOF_NOCONFIRMATION = 0x10; // Don't prompt the user

And you can use this function like this:

var shf = new Win32.SHFILEOPSTRUCT();
shf.wFunc = Win32.FO_DELETE;
shf.fFlags = Win32.FOF_ALLOWUNDO;
shf.pFrom = @"c:\myfile.txt" + '\0' + '\0';
Win32.SHFileOperation(ref shf);

The pFrom parameter can be either file or folder.

Happy programming! :)

* This is not 100% true. We can do this by using Microsoft.VisualBasic namespace. And here is the implementation.

using Microsoft.VisualBasic;

string path = @"c:\myfile.txt";
FileIO.FileSystem.DeleteDirectory(path,
    FileIO.UIOption.OnlyErrorDialogs,
    RecycleOption.SendToRecycleBin);

Related Content

  1. CaptureItPlus – A screen capture utility
  2. How to use TaskDialog API in C#
  3. How to turn off monitor programmatically using C#
  4. Setting an application on top other windows using C#
  5. How to record sound using C#

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Anuraj Parameswaran
Technical Lead
India India
Working as Tech. Lead

My blog : dotnetthoughts.net.
You can follow me in twitter : @anuraj

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170924.2 | Last Updated 24 Sep 2012
Article Copyright 2012 by Anuraj Parameswaran
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid