欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

程序员文章站 2023-11-18 20:28:10
本文实例讲述了c#实现的文件操作封装类。分享给大家供大家参考,具体如下: 最近发现群共享里面有个c# 文件操作封装类,其方法是调用windows api 来操作的文件的删...

本文实例讲述了c#实现的文件操作封装类。分享给大家供大家参考,具体如下:

最近发现群共享里面有个c# 文件操作封装类,其方法是调用windows api 来操作的文件的删除、移动、复制、重命名操作。下载下来一试,发现果然不错,特在此记录,以防丢失!

文件操作类代码如下:

using system;
using system.runtime.interopservices;
using system.io;
namespace lxfile
{
  /// <summary>
  /// 文件操作代理,该类提供类似于windows的文件操作体验
  /// </summary>
  public class fileoperateproxy
  {
    #region 【内部类型定义】
    private struct shfileopstruct
    {
      public intptr hwnd;     //父窗口句柄
      public wfunc wfunc;     //要执行的动作
      public string pfrom;    //源文件路径,可以是多个文件,以结尾符号"\0"结束
      public string pto;     //目标路径,可以是路径或文件名
      public fileop_flags fflags;       //标志,附加选项
      public bool fanyoperationsaborted;   //是否可被中断
      public intptr hnamemappings;      //文件映射名字,可在其它 shell 函数中使用
      public string lpszprogresstitle;    // 只在 fof_simpleprogress 时,指定对话框的标题。
    }
    private enum wfunc
    {
      fo_move = 0x0001,  //移动文件
      fo_copy = 0x0002,  //复制文件
      fo_delete = 0x0003, //删除文件,只是用pfrom
      fo_rename = 0x0004 //文件重命名
    }
    private enum fileop_flags
    {
      fof_multidestfiles = 0x0001,  //pto 指定了多个目标文件,而不是单个目录
      fof_confirmmouse = 0x0002,
      fof_silent = 0x0044,      // 不显示一个进度对话框
      fof_renameoncollision = 0x0008, // 碰到有抵触的名字时,自动分配前缀
      fof_noconfirmation = 0x10,   // 不对用户显示提示
      fof_wantmappinghandle = 0x0020, // 填充 hnamemappings 字段,必须使用 shfreenamemappings 释放
      fof_allowundo = 0x40,      // 允许撤销
      fof_filesonly = 0x0080,     // 使用 *.* 时, 只对文件操作
      fof_simpleprogress = 0x0100,  // 简单进度条,意味者不显示文件名。
      fof_noconfirmmkdir = 0x0200,  // 建新目录时不需要用户确定
      fof_noerrorui = 0x0400,     // 不显示出错用户界面
      fof_nocopysecurityattribs = 0x0800,   // 不复制 nt 文件的安全属性
      fof_norecursion = 0x1000    // 不递归目录
    }
    #endregion 【内部类型定义】
    #region 【dllimport】
    [dllimport("shell32.dll")]
    private static extern int shfileoperation(ref shfileopstruct lpfileop);
    #endregion 【dllimport】
    #region 【删除文件操作】
    /// <summary>
    /// 删除单个文件。
    /// </summary>
    /// <param name="filename">删除的文件名</param>
    /// <param name="torecycle">指示是将文件放入回收站还是永久删除,true-放入回收站,false-永久删除</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认删除对话框,false-不显示确认删除对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框,true-显示,false-不显示。该参数当指定永久删除文件时有效</param>
    /// <param name="errormsg">反馈错误消息的字符串</param>
    /// <returns>操作执行结果标识,删除文件成功返回0,否则,返回错误代码</returns>
    public static int deletefile(string filename, bool torecycle, bool showdialog, bool showprogress, ref string errormsg)
    {
      try
      {
        string fname = getfullname(filename);
        return todelete(fname, torecycle, showdialog, showprogress, ref errormsg);
      }
      catch (exception ex)
      {
        errormsg = ex.message;
        return -200;
      }
    }
    /// <summary>
    /// 删除一组文件。
    /// </summary>
    /// <param name="filenames">字符串数组,表示一组文件名</param>
    /// <param name="torecycle">指示是将文件放入回收站还是永久删除,true-放入回收站,false-永久删除</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认删除对话框,false-不显示确认删除对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框,true-显示,false-不显示。该参数当指定永久删除文件时有效</param>
    /// <param name="errormsg">反馈错误消息的字符串</param>
    /// <returns>操作执行结果标识,删除文件成功返回0,否则,返回错误代码</returns>
    public static int deletefiles(string[] filenames, bool torecycle, bool showdialog, bool showprogress, ref string errormsg)
    {
      try
      {
        string fname = "";
        foreach (string str in filenames)
        {
          fname += getfullname(str) + "\0";   //组件文件组字符串
        }
        return todelete(fname, torecycle, showdialog, showprogress, ref errormsg);
      }
      catch (exception ex)
      {
        errormsg = ex.message;
        return -200;
      }
    }
    #endregion 【删除文件操作】
    #region 【移动文件操作】
    /// <summary>
    /// 移动一个文件到指定路径下
    /// </summary>
    /// <param name="sourcefilename">要移动的文件名</param>
    /// <param name="destinationpath">移动到的目的路径</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认对话框,false-不显示确认对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框</param>
    /// <param name="autorename">指示当文件名重复时,是否自动为新文件加上后缀名</param>
    /// <param name="errormsg">反馈错误消息的字符串</param>
    /// <returns>返回移动操作是否成功的标识,成功返回0,失败返回错误代码</returns>
    public static int movefile(string sourcefilename, string destinationpath, bool showdialog, bool showprogress, bool autorename, ref string errormsg)
    {
      try
      {
        string sfname = getfullname(sourcefilename);
        string dfname = getfullname(destinationpath);
        return tomoveorcopy(wfunc.fo_move, sfname, dfname, showdialog, showprogress, autorename, ref errormsg);
      }
      catch (exception ex)
      {
        errormsg = ex.message;
        return -200;
      }
    }
    /// <summary>
    /// 移动一组文件到指定的路径下
    /// </summary>
    /// <param name="sourcefilenames">要移动的文件名数组</param>
    /// <param name="destinationpath">移动到的目的路径</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认对话框,false-不显示确认对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框</param>
    /// <param name="autorename">指示当文件名重复时,是否自动为新文件加上后缀名</param>
    /// <param name="errormsg">反馈错误消息的字符串</param>
    /// <returns>返回移动操作是否成功的标识,成功返回0,失败返回错误代码,-200:表示其他异常</returns>
    public static int movefiles(string[] sourcefilenames, string destinationpath, bool showdialog, bool showprogress, bool autorename, ref string errormsg)
    {
      try
      {
        string sfname = "";
        foreach (string str in sourcefilenames)
        {
          sfname += getfullname(str) + "\0";  //组件文件组字符串
        }
        string dfname = getfullname(destinationpath);
        return tomoveorcopy(wfunc.fo_move, sfname, dfname, showdialog, showprogress, autorename, ref errormsg);
      }
      catch (exception ex)
      {
        errormsg = ex.message;
        return -200;
      }
    }
    #endregion 【移动文件操作】
    #region 【复制文件操作】
    /// <summary>
    /// 复制一个文件到指定的文件名或路径
    /// </summary>
    /// <param name="sourcefilename">要复制的文件名</param>
    /// <param name="destinationfilename">复制到的目的文件名或路径</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认对话框,false-不显示确认对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框</param>
    /// <param name="autorename">指示当文件名重复时,是否自动为新文件加上后缀名</param>
    /// <returns>返回移动操作是否成功的标识,成功返回0,失败返回错误代码,-200:表示其他异常</returns>
    public static int copyfile(string sourcefilename, string destinationfilename, bool showdialog, bool showprogress, bool autorename, ref string errormsg)
    {
      try
      {
        string sfname = getfullname(sourcefilename);
        string dfname = getfullname(destinationfilename);
        return tomoveorcopy(wfunc.fo_copy, sfname, dfname, showdialog, showprogress, autorename, ref errormsg);
      }
      catch (exception ex)
      {
        errormsg = ex.message;
        return -200;
      }
    }
    /// <summary>
    /// 复制一组文件到指定的路径
    /// </summary>
    /// <param name="sourcefilenames">要复制的文件名数组</param>
    /// <param name="destinationpath">复制到的目的路径</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认对话框,false-不显示确认对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框</param>
    /// <param name="autorename">指示当文件名重复时,是否自动为新文件加上后缀名</param>
    /// <returns>返回移动操作是否成功的标识,成功返回0,失败返回错误代码,-200:表示其他异常</returns>
    public static int copyfiles(string[] sourcefilenames, string destinationpath, bool showdialog, bool showprogress, bool autorename, ref string errormsg)
    {
      try
      {
        string sfname = "";
        foreach (string str in sourcefilenames)
        {
          sfname += getfullname(str) + "\0";   //组件文件组字符串
        }
        string dfname = getfullname(destinationpath);
        return tomoveorcopy(wfunc.fo_copy, sfname, dfname, showdialog, showprogress, autorename, ref errormsg);
      }
      catch (exception ex)
      {
        errormsg = ex.message;
        return -200;
      }
    }
    #endregion 【复制文件操作】
    #region 【重命名文件】
    /// <summary>
    /// 重命名一个文件为新名称,建议您使用更方便的microsoft.visualbasic.filesystem.rename();替换该方法
    /// </summary>
    /// <param name="sourcefilename">要复制的文件名</param>
    /// <param name="destinationfilename">复制到的目的文件名或路径</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认对话框,false-不显示确认对话框</param>
    /// <returns>返回移动操作是否成功的标识,成功返回0,失败返回错误代码,-200:表示其他异常</returns>
    [obsolete("建议使用 microsoft.visualbasic.filesystem.rename()方法")]
    public static int renamefile(string sourcefilename, string destinationfilename, bool showdialog, ref string errormsg)
    {
      try
      {
        shfileopstruct lpfileop = new shfileopstruct();
        lpfileop.wfunc = wfunc.fo_rename;
        lpfileop.pfrom = getfullname(sourcefilename) + "\0\0";     //将文件名以结尾字符"\0\0"结束
        lpfileop.pto = getfullname(destinationfilename) + "\0\0";
        lpfileop.fflags = fileop_flags.fof_noerrorui;
        if (!showdialog)
          lpfileop.fflags |= fileop_flags.fof_noconfirmation;   //设定不显示提示对话框
        lpfileop.fanyoperationsaborted = true;
        int n = shfileoperation(ref lpfileop);
        if (n == 0)
          return 0;
        string tmp = geterrorstring(n);
        errormsg = string.format("{0}({1})", tmp, sourcefilename);
        return n;
      }
      catch (exception ex)
      {
        errormsg = ex.message;
        return -200;
      }
    }
    /// <summary>
    /// 利用microsoft.visualbasic.filesystem.rename()方法实现
    /// </summary>
    /// <param name="filepath"></param>
    /// <param name="newfilename"></param>
    public static void renamefile(string filepath, string newfilename)
    {
      try
      {
        string extensname = path.getextension(filepath);
        string newname = newfilename + extensname;
        microsoft.visualbasic.fileio.filesystem.renamefile(filepath, newname);
      }
      catch (exception ex)
      {
        throw ex;
      }
    }
    #endregion 【重命名文件】
    /// <summary>
    /// 删除单个或多个文件
    /// </summary>
    /// <param name="filename">删除的文件名,如果是多个文件,文件名之间以字符串结尾符'\0'隔开</param>
    /// <param name="torecycle">指示是将文件放入回收站还是永久删除,true-放入回收站,false-永久删除</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认删除对话框,false-不显示确认删除对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框,true-显示,false-不显示。该参数当指定永久删除文件时有效</param>
    /// <param name="errormsg">反馈错误消息的字符串</param>
    /// <returns>操作执行结果标识,删除文件成功返回0,否则,返回错误代码</returns>
    private static int todelete(string filename, bool torecycle, bool showdialog, bool showprogress, ref string errormsg)
    {
      shfileopstruct lpfileop = new shfileopstruct();
      lpfileop.wfunc = wfunc.fo_delete;
      lpfileop.pfrom = filename + "\0";    //将文件名以结尾字符"\0"结束
      lpfileop.fflags = fileop_flags.fof_noerrorui;
      if (torecycle)
        lpfileop.fflags |= fileop_flags.fof_allowundo; //设定删除到回收站
      if (!showdialog)
        lpfileop.fflags |= fileop_flags.fof_noconfirmation;   //设定不显示提示对话框
      if (!showprogress)
        lpfileop.fflags |= fileop_flags.fof_silent;   //设定不显示进度对话框
      lpfileop.fanyoperationsaborted = true;
      int n = shfileoperation(ref lpfileop);
      if (n == 0)
        return 0;
      string tmp = geterrorstring(n);
      //.av 文件正常删除了但也提示 402 错误,不知道为什么。屏蔽之。
      if ((filename.tolower().endswith(".av") && n.tostring("x") == "402"))
        return 0;
      errormsg = string.format("{0}({1})", tmp, filename);
      return n;
    }
    /// <summary>
    /// 移动或复制一个或多个文件到指定路径下
    /// </summary>
    /// <param name="flag">操作类型,是移动操作还是复制操作</param>
    /// <param name="sourcefilename">要移动或复制的文件名,如果是多个文件,文件名之间以字符串结尾符'\0'隔开</param>
    /// <param name="destinationfilename">移动到的目的位置</param>
    /// <param name="showdialog">指示是否显示确认对话框,true-显示确认对话框,false-不显示确认对话框</param>
    /// <param name="showprogress">指示是否显示进度对话框</param>
    /// <param name="autorename">指示当文件名重复时,是否自动为新文件加上后缀名</param>
    /// <param name="errormsg">反馈错误消息的字符串</param>
    /// <returns>返回移动操作是否成功的标识,成功返回0,失败返回错误代码</returns>
    private static int tomoveorcopy(wfunc flag, string sourcefilename, string destinationfilename, bool showdialog, bool showprogress, bool autorename, ref string errormsg)
    {
      shfileopstruct lpfileop = new shfileopstruct();
      lpfileop.wfunc = flag;
      lpfileop.pfrom = sourcefilename + "\0";     //将文件名以结尾字符"\0\0"结束
      lpfileop.pto = destinationfilename + "\0\0";
      lpfileop.fflags = fileop_flags.fof_noerrorui;
      lpfileop.fflags |= fileop_flags.fof_noconfirmmkdir; //指定在需要时可以直接创建路径
      if (!showdialog)
        lpfileop.fflags |= fileop_flags.fof_noconfirmation;   //设定不显示提示对话框
      if (!showprogress)
        lpfileop.fflags |= fileop_flags.fof_silent;   //设定不显示进度对话框
      if (autorename)
        lpfileop.fflags |= fileop_flags.fof_renameoncollision; //自动为重名文件添加名称后缀
      lpfileop.fanyoperationsaborted = true;
      int n = shfileoperation(ref lpfileop);
      if (n == 0)
        return 0;
      string tmp = geterrorstring(n);
      errormsg = string.format("{0}({1})", tmp, sourcefilename);
      return n;
    }
    /// <summary>
    /// 获取一个文件的全名
    /// </summary>
    /// <param name="filename">文件名</param>
    /// <returns>返回生成文件的完整路径名</returns>
    private static string getfullname(string filename)
    {
      fileinfo fi = new fileinfo(filename);
      return fi.fullname;
    }
    /// <summary>
    /// 解释错误代码
    /// </summary>
    /// <param name="n">代码号</param>
    /// <returns>返回关于错误代码的文字描述</returns>
    private static string geterrorstring(int n)
    {
      if (n == 0) return string.empty;
      switch (n)
      {
        case 2:
          return "系统找不到指定的文件。";
        case 7:
          return "存储控制块被销毁。您是否选择的“取消”操作?";
        case 113:
          return "文件已存在!";
        case 115:
          return "重命名文件操作,原始文件和目标文件必须具有相同的路径名。不能使用相对路径。";
        case 117:
          return "i/o控制错误";
        case 123:
          return "指定了重复的文件名";
        case 116:
          return "the source is a root directory, which cannot be moved or renamed.";
        case 118:
          return "security settings denied access to the source.";
        case 124:
          return "the path in the source or destination or both was invalid.";
        case 65536:
          return "an unspecified error occurred on the destination.";
        case 1026:
          return "在试图移动或拷贝一个不存在的文件.";
        case 1223:
          return "操作被取消!";
        default:
          return "未识别的错误代码:" + n;
      }
    }
  }
}

附:完整实例代码点击此处本站下载

更多关于c#相关内容感兴趣的读者可查看本站专题:《c#文件操作常用技巧汇总》、《c#遍历算法与技巧总结》、《c#程序设计之线程使用技巧总结》、《c#操作excel技巧总结》、《c#中xml文件操作技巧汇总》、《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#数组操作技巧总结》及《c#面向对象程序设计入门教程

希望本文所述对大家c#程序设计有所帮助。