1

制作一个具有大量功能的文件浏览器,回来微调我的一些方法来找到它:

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

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

有什么方法可以在没有过多提示的情况下实现这一目标?还是我必须深入研究 SHFILEOPSTRUCT?

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

4

2 回答 2

4

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

于 2012-05-16T22:32:37.873 回答
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 站点上找到了 SHFILEOPSTRUCT 的布局,并且在该链接上,有一些关于所用字符串声明的注释。

出色地。在我的 Win7 64 位上进行了测试,需要删除一个目录。奇迹般有效....

于 2012-05-17T10:13:13.443 回答