当前位置: 移动技术网 > IT编程>开发语言>c# > C#封装的常用文件操作类实例

C#封装的常用文件操作类实例

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

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

这个c#类封装了我们经常能用到的文件操作方法,包括读写文件、获取文件扩展名、复制文件、追加内容到文件、删除文件、移动文件、创建目录、递归删除文件及目录、列目录、列文件等,不可多得。

using system;
using system.text;
using system.web;
using system.io;
namespace dotnet.utilities
{
  public class fileoperate
  {
    #region 写文件
    protected void write_txt(string filename, string content)
    {
      encoding code = encoding.getencoding("gb2312");
      string htmlfilename = httpcontext.current.server.mappath("precious\\" + filename + ".txt"); //保存文件的路径
      string str = content;
      streamwriter sw = null;
      {
        try
        {
          sw = new streamwriter(htmlfilename, false, code);
          sw.write(str);
          sw.flush();
        }
        catch { }
      }
      sw.close();
      sw.dispose();
    }
    #endregion
    #region 读文件
    protected string read_txt(string filename)
    {
      encoding code = encoding.getencoding("gb2312");
      string temp = httpcontext.current.server.mappath("precious\\" + filename + ".txt");
      string str = "";
      if (file.exists(temp))
      {
        streamreader sr = null;
        try
        {
          sr = new streamreader(temp, code);
          str = sr.readtoend(); // 读取文件
        }
        catch { }
        sr.close();
        sr.dispose();
      }
      else
      {
        str = "";
      }
 
      return str;
    }
    #endregion
    #region 取得文件后缀名
    /****************************************
     * 函数名称:getpostfixstr
     * 功能说明:取得文件后缀名
     * 参  数:filename:文件名称
     * 调用示列:
     *      string filename = "aaa.aspx";    
     *      string s = dotnet.utilities.fileoperate.getpostfixstr(filename);    
    *****************************************/
    /// <summary>
    /// 取后缀名
    /// </summary>
    /// <param name="filename">文件名</param>
    /// <returns>.gif|.html格式</returns>
    public static string getpostfixstr(string filename)
    {
      int start = filename.lastindexof(".");
      int length = filename.length;
      string postfix = filename.substring(start, length - start);
      return postfix;
    }
    #endregion
    #region 写文件
    /****************************************
     * 函数名称:writefile
     * 功能说明:当文件不存时,则创建文件,并追加文件
     * 参  数:path:文件路径,strings:文本内容
     * 调用示列:
     *      string path = server.mappath("default2.aspx");   
     *      string strings = "这是我写的内容啊";
     *      dotnet.utilities.fileoperate.writefile(path,strings);
    *****************************************/
    /// <summary>
    /// 写文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="strings">文件内容</param>
    public static void writefile(string path, string strings)
    {
      if (!system.io.file.exists(path))
      {
        system.io.filestream f = system.io.file.create(path);
        f.close();
        f.dispose();
      }
      system.io.streamwriter f2 = new system.io.streamwriter(path, true, system.text.encoding.utf8);
      f2.writeline(strings);
      f2.close();
      f2.dispose();
 
    }
    #endregion
    #region 读文件
    /****************************************
     * 函数名称:readfile
     * 功能说明:读取文本内容
     * 参  数:path:文件路径
     * 调用示列:
     *      string path = server.mappath("default2.aspx");   
     *      string s = dotnet.utilities.fileoperate.readfile(path);
    *****************************************/
    /// <summary>
    /// 读文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <returns></returns>
    public static string readfile(string path)
    {
      string s = "";
      if (!system.io.file.exists(path))
        s = "不存在相应的目录";
      else
      {
        streamreader f2 = new streamreader(path, system.text.encoding.getencoding("gb2312"));
        s = f2.readtoend();
        f2.close();
        f2.dispose();
      }
      return s;
    }
    #endregion
    #region 追加文件
    /****************************************
     * 函数名称:fileadd
     * 功能说明:追加文件内容
     * 参  数:path:文件路径,strings:内容
     * 调用示列:
     *      string path = server.mappath("default2.aspx");  
     *      string strings = "新追加内容";
     *      dotnet.utilities.fileoperate.fileadd(path, strings);
    *****************************************/
    /// <summary>
    /// 追加文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="strings">内容</param>
    public static void fileadd(string path, string strings)
    {
      streamwriter sw = file.appendtext(path);
      sw.write(strings);
      sw.flush();
      sw.close();
      sw.dispose();
    }
    #endregion
    #region 拷贝文件
    /****************************************
     * 函数名称:filecoppy
     * 功能说明:拷贝文件
     * 参  数:orignfile:原始文件,newfile:新文件路径
     * 调用示列:
     *      string orignfile = server.mappath("default2.aspx");  
     *      string newfile = server.mappath("default3.aspx");
     *      dotnet.utilities.fileoperate.filecoppy(orignfile, newfile);
    *****************************************/
    /// <summary>
    /// 拷贝文件
    /// </summary>
    /// <param name="orignfile">原始文件</param>
    /// <param name="newfile">新文件路径</param>
    public static void filecoppy(string orignfile, string newfile)
    {
      file.copy(orignfile, newfile, true);
    }
    #endregion
    #region 删除文件
    /****************************************
     * 函数名称:filedel
     * 功能说明:删除文件
     * 参  数:path:文件路径
     * 调用示列:
     *      string path = server.mappath("default3.aspx");  
     *      dotnet.utilities.fileoperate.filedel(path);
    *****************************************/
    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="path">路径</param>
    public static void filedel(string path)
    {
      file.delete(path);
    }
    #endregion
    #region 移动文件
    /****************************************
     * 函数名称:filemove
     * 功能说明:移动文件
     * 参  数:orignfile:原始路径,newfile:新文件路径
     * 调用示列:
     *      string orignfile = server.mappath("../说明.txt");  
     *      string newfile = server.mappath("../../说明.txt");
     *      dotnet.utilities.fileoperate.filemove(orignfile, newfile);
    *****************************************/
    /// <summary>
    /// 移动文件
    /// </summary>
    /// <param name="orignfile">原始路径</param>
    /// <param name="newfile">新路径</param>
    public static void filemove(string orignfile, string newfile)
    {
      file.move(orignfile, newfile);
    }
    #endregion
    #region 在当前目录下创建目录
    /****************************************
     * 函数名称:foldercreate
     * 功能说明:在当前目录下创建目录
     * 参  数:orignfolder:当前目录,newfloder:新目录
     * 调用示列:
     *      string orignfolder = server.mappath("test/");  
     *      string newfloder = "new";
     *      dotnet.utilities.fileoperate.foldercreate(orignfolder, newfloder);
    *****************************************/
    /// <summary>
    /// 在当前目录下创建目录
    /// </summary>
    /// <param name="orignfolder">当前目录</param>
    /// <param name="newfloder">新目录</param>
    public static void foldercreate(string orignfolder, string newfloder)
    {
      directory.setcurrentdirectory(orignfolder);
      directory.createdirectory(newfloder);
    }
    /// <summary>
    /// 创建文件夹
    /// </summary>
    /// <param name="path"></param>
    public static void foldercreate(string path)
    {
      // 判断目标目录是否存在如果不存在则新建之
      if (!directory.exists(path))
        directory.createdirectory(path);
    }
    #endregion
    #region 创建目录
    public static void filecreate(string path)
    {
      fileinfo createfile = new fileinfo(path); //创建文件
      if (!createfile.exists)
      {
        filestream fs = createfile.create();
        fs.close();
      }
    }
    #endregion
    #region 递归删除文件夹目录及文件
    /****************************************
     * 函数名称:deletefolder
     * 功能说明:递归删除文件夹目录及文件
     * 参  数:dir:文件夹路径
     * 调用示列:
     *      string dir = server.mappath("test/"); 
     *      dotnet.utilities.fileoperate.deletefolder(dir);   
    *****************************************/
    /// <summary>
    /// 递归删除文件夹目录及文件
    /// </summary>
    /// <param name="dir"></param> 
    /// <returns></returns>
    public static void deletefolder(string dir)
    {
      if (directory.exists(dir)) //如果存在这个文件夹删除之
      {
        foreach (string d in directory.getfilesystementries(dir))
        {
          if (file.exists(d))
            file.delete(d); //直接删除其中的文件            
          else
            deletefolder(d); //递归删除子文件夹
        }
        directory.delete(dir, true); //删除已空文件夹        
      }
    }
    #endregion
    #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
    /****************************************
     * 函数名称:copydir
     * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
     * 参  数:srcpath:原始路径,aimpath:目标文件夹
     * 调用示列:
     *      string srcpath = server.mappath("test/"); 
     *      string aimpath = server.mappath("test1/");
     *      dotnet.utilities.fileoperate.copydir(srcpath,aimpath); 
    *****************************************/
    /// <summary>
    /// 指定文件夹下面的所有内容copy到目标文件夹下面
    /// </summary>
    /// <param name="srcpath">原始路径</param>
    /// <param name="aimpath">目标文件夹</param>
    public static void copydir(string srcpath, string aimpath)
    {
      try
      {
        // 检查目标目录是否以目录分割字符结束如果不是则添加之
        if (aimpath[aimpath.length - 1] != path.directoryseparatorchar)
          aimpath += path.directoryseparatorchar;
        // 判断目标目录是否存在如果不存在则新建之
        if (!directory.exists(aimpath))
          directory.createdirectory(aimpath);
        // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
        //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
        //string[] filelist = directory.getfiles(srcpath);
        string[] filelist = directory.getfilesystementries(srcpath);
        //遍历所有的文件和目录
        foreach (string file in filelist)
        {
          //先当作目录处理如果存在这个目录就递归copy该目录下面的文件
          if (directory.exists(file))
            copydir(file, aimpath + path.getfilename(file));
          //否则直接copy文件
          else
            file.copy(file, aimpath + path.getfilename(file), true);
        }
      }
      catch (exception ee)
      {
        throw new exception(ee.tostring());
      }
    }
    #endregion
    #region 获取指定文件夹下所有子目录及文件(树形)
    /****************************************
     * 函数名称:getfoldall(string path)
     * 功能说明:获取指定文件夹下所有子目录及文件(树形)
     * 参  数:path:详细路径
     * 调用示列:
     *      string strdirlist = server.mappath("templates");   
     *      this.literal1.text = dotnet.utilities.fileoperate.getfoldall(strdirlist); 
    *****************************************/
    /// <summary>
    /// 获取指定文件夹下所有子目录及文件
    /// </summary>
    /// <param name="path">详细路径</param>
    public static string getfoldall(string path)
    {
      string str = "";
      directoryinfo thisone = new directoryinfo(path);
      str = listtreeshow(thisone, 0, str);
      return str;
    }
    /// <summary>
    /// 获取指定文件夹下所有子目录及文件函数
    /// </summary>
    /// <param name="thedir">指定目录</param>
    /// <param name="nlevel">默认起始值,调用时,一般为0</param>
    /// <param name="rn">用于迭加的传入值,一般为空</param>
    /// <returns></returns>
    public static string listtreeshow(directoryinfo thedir, int nlevel, string rn)//递归目录 文件
    {
      directoryinfo[] subdirectories = thedir.getdirectories();//获得目录
      foreach (directoryinfo dirinfo in subdirectories)
      {
        if (nlevel == 0)
        {
          rn += "├";
        }
        else
        {
          string _s = "";
          for (int i = 1; i <= nlevel; i++)
          {
            _s += "│ ";
          }
          rn += _s + "├";
        }
        rn += "<b>" + dirinfo.name.tostring() + "</b><br />";
        fileinfo[] fileinfo = dirinfo.getfiles();  //目录下的文件
        foreach (fileinfo finfo in fileinfo)
        {
          if (nlevel == 0)
          {
            rn += "│ ├";
          }
          else
          {
            string _f = "";
            for (int i = 1; i <= nlevel; i++)
            {
              _f += "│ ";
            }
            rn += _f + "│ ├";
          }
          rn += finfo.name.tostring() + " <br />";
        }
        rn = listtreeshow(dirinfo, nlevel + 1, rn);
 
      }
      return rn;
    }
 
    /****************************************
     * 函数名称:getfoldall(string path)
     * 功能说明:获取指定文件夹下所有子目录及文件(下拉框形)
     * 参  数:path:详细路径
     * 调用示列:
     *      string strdirlist = server.mappath("templates");   
     *      this.literal2.text = dotnet.utilities.fileoperate.getfoldall(strdirlist,"tpl","");
    *****************************************/
    /// <summary>
    /// 获取指定文件夹下所有子目录及文件(下拉框形)
    /// </summary>
    /// <param name="path">详细路径</param>
    ///<param name="dropname">下拉列表名称</param>
    ///<param name="tplpath">默认选择模板名称</param>
    public static string getfoldall(string path, string dropname, string tplpath)
    {
      string strdrop = "<select name=\"" + dropname + "\" id=\"" + dropname + "\"><option value=\"\">--请选择详细模板--</option>";
      string str = "";
      directoryinfo thisone = new directoryinfo(path);
      str = listtreeshow(thisone, 0, str, tplpath);
      return strdrop + str + "</select>";
    }
    /// <summary>
    /// 获取指定文件夹下所有子目录及文件函数
    /// </summary>
    /// <param name="thedir">指定目录</param>
    /// <param name="nlevel">默认起始值,调用时,一般为0</param>
    /// <param name="rn">用于迭加的传入值,一般为空</param>
    /// <param name="tplpath">默认选择模板名称</param>
    /// <returns></returns>
    public static string listtreeshow(directoryinfo thedir, int nlevel, string rn, string tplpath)//递归目录 文件
    {
      directoryinfo[] subdirectories = thedir.getdirectories();//获得目录
      foreach (directoryinfo dirinfo in subdirectories)
      {
        rn += "<option value=\"" + dirinfo.name.tostring() + "\"";
        if (tplpath.tolower() == dirinfo.name.tostring().tolower())
        {
          rn += " selected ";
        }
        rn += ">";
        if (nlevel == 0)
        {
          rn += "┣";
        }
        else
        {
          string _s = "";
          for (int i = 1; i <= nlevel; i++)
          {
            _s += "│ ";
          }
          rn += _s + "┣";
        }
        rn += "" + dirinfo.name.tostring() + "</option>";
 
        fileinfo[] fileinfo = dirinfo.getfiles();  //目录下的文件
        foreach (fileinfo finfo in fileinfo)
        {
          rn += "<option value=\"" + dirinfo.name.tostring() + "/" + finfo.name.tostring() + "\"";
          if (tplpath.tolower() == finfo.name.tostring().tolower())
          {
            rn += " selected ";
          }
          rn += ">";
          if (nlevel == 0)
          {
            rn += "│ ├";
          }
          else
          {
            string _f = "";
            for (int i = 1; i <= nlevel; i++)
            {
              _f += "│ ";
            }
            rn += _f + "│ ├";
          }
          rn += finfo.name.tostring() + "</option>";
        }
        rn = listtreeshow(dirinfo, nlevel + 1, rn, tplpath);
 
      }
      return rn;
    }
    #endregion
    #region 获取文件夹大小
    /****************************************
     * 函数名称:getdirectorylength(string dirpath)
     * 功能说明:获取文件夹大小
     * 参  数:dirpath:文件夹详细路径
     * 调用示列:
     *      string path = server.mappath("templates");
     *      response.write(dotnet.utilities.fileoperate.getdirectorylength(path));   
    *****************************************/
    /// <summary>
    /// 获取文件夹大小
    /// </summary>
    /// <param name="dirpath">文件夹路径</param>
    /// <returns></returns>
    public static long getdirectorylength(string dirpath)
    {
      if (!directory.exists(dirpath))
        return 0;
      long len = 0;
      directoryinfo di = new directoryinfo(dirpath);
      foreach (fileinfo fi in di.getfiles())
      {
        len += fi.length;
      }
      directoryinfo[] dis = di.getdirectories();
      if (dis.length > 0)
      {
        for (int i = 0; i < dis.length; i++)
        {
          len += getdirectorylength(dis[i].fullname);
        }
      }
      return len;
    }
    #endregion
    #region 获取指定文件详细属性
    /****************************************
     * 函数名称:getfileattibe(string filepath)
     * 功能说明:获取指定文件详细属性
     * 参  数:filepath:文件详细路径
     * 调用示列:
     *      string file = server.mappath("robots.txt"); 
     *      response.write(dotnet.utilities.fileoperate.getfileattibe(file));    
    *****************************************/
    /// <summary>
    /// 获取指定文件详细属性
    /// </summary>
    /// <param name="filepath">文件详细路径</param>
    /// <returns></returns>
    public static string getfileattibe(string filepath)
    {
      string str = "";
      system.io.fileinfo objfi = new system.io.fileinfo(filepath);
      str += "详细路径:" + objfi.fullname + "<br>文件名称:" + objfi.name + "<br>文件长度:" + objfi.length.tostring() + "字节<br>创建时间" + objfi.creationtime.tostring() + "<br>最后访问时间:" + objfi.lastaccesstime.tostring() + "<br>修改时间:" + objfi.lastwritetime.tostring() + "<br>所在目录:" + objfi.directoryname + "<br>扩展名:" + objfi.extension;
      return str;
    }
    #endregion
  }
}

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

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

相关文章:

验证码:
移动技术网