当前位置: 首页 > news >正文

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 Constpublic const int FO_DELETE = 3;public const int FOF_ALLOWUNDO = 0x40;public const int FOF_NOCONFIRMATION = 0x10;#endregion#region Public Static Methodpublic 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}
}

http://www.lryc.cn/news/521194.html

相关文章:

  • GESP2024年12月认证C++六级( 第三部分编程题(1)树上游走)
  • Redis数据结构服务器
  • 【向量数据库 Milvus】centos8源码安装和部署 Milvus 2.5.3
  • MySQL数据库(SQL分类)
  • C++实现设计模式---原型模式 (Prototype)
  • 鸿蒙面试 2025-01-10
  • Linux Top 命令 load average 指标解读
  • 31_搭建Redis分片集群
  • 客户案例 | Ansys与索尼半导体解决方案公司合作推进自动驾驶汽车基于场景的感知测试
  • c#-Halcon入门教程——标定
  • MC1.12.2 macOS高清修复OptiFine运行崩溃
  • 精选2款.NET开源的博客系统
  • 转运机器人在物流仓储行业的优势特点
  • 简识MySQL的InnoDB Locking锁的分类
  • 如何通过openssl生成.crt和.key
  • .NetCore 使用 NPOI 读取带有图片的excel数据
  • linux上使用update-alternatives来选择软件版本
  • 【Elasticsearch复合查询】
  • Java List去重:Stream、HashMap与TreeSet对比分析
  • 大师课程:专业角色AE+AI动画动态设计关键帧学院视频课程 Key Frame Academy – Character Animation Launchpad
  • 游戏盾SDK如何防护APP攻击
  • Spring Boot 3.x 整合 Logback 日志框架(支持异步写入)
  • 从0开始学习搭网站第二天
  • 【Unity-Animator】通过 StateMachineBehaviour 实现回调
  • 鸿蒙中自定义slider实现字体大小变化
  • 数据结构与算法之栈: LeetCode 71. 简化路径 (Ts版)
  • STM32-笔记40-BKP(备份寄存器)
  • NAS中不同RAID级别特点与适用场景
  • node.js的进程保活
  • meta name=“viewport“ content=“width=device-width, initial-scale=1.0“