C#实现删除文件和目录到回收站
作者:秋月的私语
这篇文章主要为大家详细介绍了如何使用C#实现删除文件和目录到回收站,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
之前在c++上遇到过这个问题,折腾许久才解决了,这次在c#上再次遇到这个问题,不过似乎容易了一些,亲测代码如下,两种删除方式都写在代码中了。
直接上完整代码:
using Microsoft.VisualBasic.FileIO; using System; using System.IO; using System.Runtime.InteropServices; namespace ceshiConsole { public class FileIOHelper { [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; } #region Dllimport [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp); #endregion #region Const public const int FO_DELETE = 3; public const int FOF_ALLOWUNDO = 0x40; public const int FOF_NOCONFIRMATION = 0x10; #endregion #region Public Static Method public static void DeleteFileToRecyclebin(string file, Boolean showConfirmDialog = false) { SHFILEOPSTRUCT shf = new SHFILEOPSTRUCT(); shf.wFunc = FO_DELETE; shf.fFlags = FOF_ALLOWUNDO; if (!showConfirmDialog) { shf.fFlags |= FOF_NOCONFIRMATION; } shf.pFrom = file + '\0' + '\0'; SHFileOperation(ref shf); } public static bool SendToRecycleBin(string path) { bool bRet = true; try { if (File.Exists(path)) { FileSystem.DeleteFile(path, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } else if (Directory.Exists(path)) { FileSystem.DeleteDirectory(path, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); } else { bRet = false; } } catch (Exception ex) { Console.WriteLine($"无法将文件/目录 {path} 移动到回收站: {ex.Message}"); bRet = false; } return bRet; } static void Main(string[] args) { DeleteFileToRecyclebin(@"C:\Users\autumoon\Desktop\test.txt"); SendToRecycleBin(@"C:\Users\autumoon\Desktop\test2.txt"); } #endregion } }
到此这篇关于C#实现删除文件和目录到回收站的文章就介绍到这了,更多相关C#删除文件和目录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!