使用FileSystem.DeleteDirectory将多个目录发送到回收站

时间:2012-05-16 22:29:25

标签: c# file-io

制作一个包含大量功能的文件浏览器,回过头来调整我的一些方法来找到它:

foreach (ListViewItem item in listView1.SelectedItems)
{
    FileSystem.DeleteDirectory(item.SubItems[3].Text,  
        UIOption.AllDialogs,
        RecycleOption.SendToRecycleBin,
        UICancelOption.ThrowException);
}

非常适合将SINGLE目录或文件发送到回收站,但它会提示每个选定的项目。不适合删除一堆文件和文件夹。

在没有多余提示的情况下实现这一目标的任何方法?或者我是否必须深入研究SHFILEOPSTRUCT?

感谢您的帮助,到目前为止,我的问题中有90%已经在这里得到了答案,这是最好的网站。

2 个答案:

答案 0 :(得分:4)

如果您不想要提示,可以使用Directory.Delete代替FileSystem方法。这将删除目录以及文件和子目录(前提是您指定要执行此操作)。

答案 1 :(得分:0)

这似乎是做你所需要的唯一方法 将文件和目录无提示地移动到回收站

using System.Runtime.InteropServices;

class Win32ApiUtils
{
    // Don't declare a value for the Pack size. If you omit it, the correct value is used when  
    // marshaling and a single SHFILEOPSTRUCT can be used for both 32-bit and 64-bit operation.
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct SHFILEOPSTRUCT
    {
        public IntPtr hwnd;
        [MarshalAs(UnmanagedType.U4)]
        public int wFunc;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string pFrom;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string pTo;            
        public ushort fFlags;
        [MarshalAs(UnmanagedType.Bool)]
        public bool fAnyOperationsAborted;
        public IntPtr hNameMappings;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string lpszProgressTitle;
   }

   [DllImport("shell32.dll", CharSet = CharSet.Auto)]
   static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
   const int FO_DELETE = 3;
   const int FOF_ALLOWUNDO = 0x40;
   const int FOF_NOCONFIRMATION = 0x10; //Don't prompt the user.; 

   public static int DeleteFilesToRecycleBin(string filename)
   {
        SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT();
        shf.wFunc = FO_DELETE;
        shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
        shf.pFrom = filename + "\0";  // <--- this "\0" is critical !!!!!
        int result = SHFileOperation(ref shf);
        // Any value different from zero is an error to lookup 
        return result;

   }

}

   foreach (ListViewItem item in listView1.SelectedItems)
   {
        int result = Win32ApiUtils.DeleteFilesToRecycleBin(item.SubItems[3].Text);
        if(result != 0) ...... // ??? throw ??? message to user and contine ???
   }

- 警告 - 此代码需要进行测试。我在PInvoke site上找到了SHFILEOPSTRUCT的布局,在该链接上有一些关于所用字符串声明的注释。

好。在我的Win7 64bit上测试了一个目录要删除。像魅力一样......