Send a File to the Recycle Bin

后端 未结 8 1168
北海茫月
北海茫月 2020-11-27 10:59

Currently I\'m using the following function

file.Delete();

But how can I use this function to send a file to the recycle bin instead of jus

8条回答
  •  长情又很酷
    2020-11-27 11:34

    I use this extension method, then I can just use a DirectoryInfo or FileInfo and delete that.

    public static class NativeMethods
    {
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
            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;
        }
        private const int FO_DELETE = 0x0003;
        private const int FOF_ALLOWUNDO = 0x0040;           // Preserve undo information, if possible. 
        private const int FOF_NOCONFIRMATION = 0x0010;      // Show no confirmation dialog box to the user      
    
    
        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
    
        static bool DeleteFileOrFolder(string path)
        {
    
    
            SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();
            fileop.wFunc = FO_DELETE;
            fileop.pFrom = path + '\0' + '\0';            
            fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
    
    
            var rc= SHFileOperation(ref fileop);
            return rc==0;
        }
    
        public static bool ToRecycleBin(this DirectoryInfo dir)
        {
            dir?.Refresh();
            if(dir is null || !dir.Exists)
            {
                return false;
            }
            else
                return DeleteFileOrFolder(dir.FullName);
        }
        public static bool ToRecycleBin(this FileInfo file)
        {
            file?.Refresh();
    
            if(file is null ||!file.Exists)
            {
                return false;
            }
            return DeleteFileOrFolder(file.FullName);
        }
    }
    

    a sample how to call it could be this:

    private void BtnDelete_Click(object sender, EventArgs e)
    {
        if(MessageBox.Show("Are you sure you would like to delete this directory?", "Delete & Close", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            return;
    
        var dir= new DirectoryInfo(directoryName);
        dir.ToRecycleBin();
    
    }
    

提交回复
热议问题