Delete File / Recycle Bin

  • Thread starter Thread starter JezB
  • Start date Start date
J

JezB

In c# code how do I delete a file while ensuring it goes into the recycle
bin for possible recovery ?
 
JezB said:
In c# code how do I delete a file while ensuring it goes into the recycle
bin for possible recovery ?
I don't think the framework offers this functionality, but you
could always P-Invoke SHFileOperation in shell32.dll.

Willem van Rumpt
 
JezB said:
Sounds a bit advanced for me - I'm only a beginner. Any guidelines how to do
that ?
I don't have Visual Studio handy here, but it off the top of my head
it would look something like this:

[DllImport("shell32.dll",CharSet = CharSet.Unicode)]
static extern int SHFileOperation([In] ref SHFILEOPSTRUCT lpFileOpStruct);

but you need the definition of SHFILEOPSTRUCT as well (and some
constants) take a look at www.pinvoke.net and search for SHFileOperation,
I'm quite sure someone already has done the work for you =)

Willem van Rumpt
 
I've taken the source for SHFileOperation from www.PInvoke.net
and it works as expected. The source below works properly:

InteropSHFileOperation fo = new InteropSHFileOperation();
fo.wFunc = InteropSHFileOperation.FO_Func.FO_DELETE;
fo.fFlags.FOF_ALLOWUNDO = true;
fo.pFrom = @"C:\test.txt";
if (fo.Execute())
{
MessageBox.Show("test.txt recycled");
}
else
{
MessageBox.Show("Unable to recycle test.txt");
}

Can you post some code, so I can look at it?

Willem van Rumpt
 
Following Shiva's suggested reference, I have this :-

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace FileHandlerNS
{
public class FileHandler
{
// Contains information that the SHFileOperation function uses to
perform file operations.
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
public UInt32 wFunc;
public string pFrom;
public string pTo;
public UInt16 fFlags;
public Int32 fAnyOperationsAborted;
public IntPtr hNameMappings;
[MarshalAs(UnmanagedType.LPWStr)]
public String lpszProgressTitle;
}

[DllImport("shell32.dll" , CharSet = CharSet.Unicode)]
public static extern Int32 SHFileOperation(ref SHFILEOPSTRUCT
lpFileOp);

const int FO_DELETE = 3;
const int FOF_ALLOWUNDO = 0x40;
const int FOF_NOCONFIRMATION = 0x10;

public static void DeleteFile(string fname)
{
SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
shf.hwnd = IntPtr.Zero;
shf.wFunc = (uint) FO_DELETE;
shf.fFlags = (ushort) FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
shf.pTo = fname;
shf.fAnyOperationsAborted = 0;
shf.hNameMappings = IntPtr.Zero;
SHFileOperation(ref shf);
}
}
}

Your example seems much simpler! But where is the definition for
InteropSHFileOperation?
 
OK I found it on the site, and your code worked - I just needed to add the
NOCONFIRMATION flag - thanks very much.
 
Back
Top