当前位置: 移动技术网 > IT编程>开发语言>c# > dotnet如何将文件删除到回收站

dotnet如何将文件删除到回收站

2019年07月18日  | 移动技术网IT编程  | 我要评论

前言

默认删除文件的时候 file.delete 是将文件永久删除,如果是一些文档,建议删除到回收站,这样用户可以自己还原 通过 shfileoperation 可以将文件放在回收站

本文提供的方法暂时只能在 x86 程序使用,此方法暂时不适合 dotnet core 程序

添加一个帮助类

 public static class recyclebin
 {
  public static void deletetorecyclebin(string file)
  {
   var shf = new shfileopstruct
   {
    wfunc = fo_delete,
    fflags = fof_allowundo | fof_noconfirmation,
    // pfrom 需要在字符串后面加两个 \0 才可以 https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/ns-shellapi-_shfileopstructa
    pfrom = file + "\0"
   };
   shfileoperation(ref shf);
  }

  [structlayout(layoutkind.sequential, charset = charset.auto, pack = 1)]
  private struct shfileopstruct
  {
   public int hwnd;
   [marshalas(unmanagedtype.u4)] public int wfunc;
   public string pfrom;
   public string pto;
   public short fflags;
   [marshalas(unmanagedtype.bool)] public bool fanyoperationsaborted;
   public int hnamemappings;
   public string lpszprogresstitle;
  }

  [dllimport("shell32.dll", charset = charset.auto)]
  private static extern int shfileoperation(ref shfileopstruct fileop);

  private const int fo_delete = 3;
  private const int fof_allowundo = 0x40;
  private const int fof_noconfirmation = 0x10;
 }

这个类里面只有一个公开方法,要求传入一个文件

下面添加一些测试的代码

  static void main(string[] args)
  {
   var folder = @"d:\lindexi\github\";
   var file = path.combine(folder, "欢迎访问我博客 blog.lindexi.com 里面有大量 uwp wpf 博客.txt");
   directory.createdirectory(folder);
   if (!file.exists(file))
   {
    file.writealltext(file, "欢迎访问我博客 blog.lindexi.com 里面有大量 uwp wpf 博客");
   }

   recyclebin.deletetorecyclebin(file);
  }

尝试运行代码

如果可以引用microsoft.visualbasic那么写起来就很清真

microsoft.visualbasic.fileio.filesystem.deletedirectory(filename or folder,
  microsoft.visualbasic.fileio.uioption.onlyerrordialogs, 
  microsoft.visualbasic.fileio.recycleoption.sendtorecyclebin);

代码在github

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网