C encapsulates common file manipulation class instances

  • 2021-01-02 21:58:18
  • OfStack

This article gives an example of the common file manipulation classes encapsulated by C#. Share to everybody for everybody reference. The details are as follows:

This C# class encapsulates the common methods we use to manipulate files, including reading and writing files, getting file extensions, copying files, appending content to files, deleting files, moving files, creating directories, recursively deleting files and directories, column directories, column files, and so on.


using System;
using System.Text;
using System.Web;
using System.IO;
namespace DotNet.Utilities
{
  public class FileOperate
  {
    #region  Write files 
    protected void Write_Txt(string FileName, string Content)
    {
      Encoding code = Encoding.GetEncoding("gb2312");
      string htmlfilename = HttpContext.Current.Server.MapPath("Precious\\" + FileName + ".txt"); // Save the path to the file 
      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  Read the file 
    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(); //  Read the file 
        }
        catch { }
        sr.Close();
        sr.Dispose();
      }
      else
      {
        str = "";
      }
 
      return str;
    }
    #endregion
    #region  Gets the file suffix name 
    /****************************************
     *  Function name: GetPostfixStr
     *  Function description: get the file suffix name 
     *  ginseng    The number: filename: The file name 
     *  Call the column: 
     *      string filename = "aaa.aspx";    
     *      string s = DotNet.Utilities.FileOperate.GetPostfixStr(filename);    
    *****************************************/
    /// <summary>
    ///  Take a suffix 
    /// </summary>
    /// <param name="filename"> The file name </param>
    /// <returns>.gif|.html format </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  Write files 
    /****************************************
     *  Function name: WriteFile
     *  Function description: when the file does not save, then create the file, and append the file 
     *  ginseng    The number: Path: The file path ,Strings: The text content 
     *  Call the column: 
     *      string Path = Server.MapPath("Default2.aspx");   
     *      string Strings = " That's what I wrote ";
     *      DotNet.Utilities.FileOperate.WriteFile(Path,Strings);
    *****************************************/
    /// <summary>
    ///  Write files 
    /// </summary>
    /// <param name="Path"> The file path </param>
    /// <param name="Strings"> The file content </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  Read the file 
    /****************************************
     *  Function name: ReadFile
     *  Function description: Read text content 
     *  ginseng    The number: Path: The file path 
     *  Call the column: 
     *      string Path = Server.MapPath("Default2.aspx");   
     *      string s = DotNet.Utilities.FileOperate.ReadFile(Path);
    *****************************************/
    /// <summary>
    ///  Read the file 
    /// </summary>
    /// <param name="Path"> The file path </param>
    /// <returns></returns>
    public static string ReadFile(string Path)
    {
      string s = "";
      if (!System.IO.File.Exists(Path))
        s = " There is no corresponding directory ";
      else
      {
        StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
        s = f2.ReadToEnd();
        f2.Close();
        f2.Dispose();
      }
      return s;
    }
    #endregion
    #region  Additional documents 
    /****************************************
     *  Function name: FileAdd
     *  Function description: Append file content 
     *  ginseng    The number: Path: The file path ,strings: content 
     *  Call the column: 
     *      string Path = Server.MapPath("Default2.aspx");  
     *      string Strings = " New append content ";
     *      DotNet.Utilities.FileOperate.FileAdd(Path, Strings);
    *****************************************/
    /// <summary>
    ///  Additional documents 
    /// </summary>
    /// <param name="Path"> The file path </param>
    /// <param name="strings"> content </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  Copy files 
    /****************************************
     *  Function name: FileCoppy
     *  Function description: Copy files 
     *  ginseng    The number: OrignFile: The original file ,NewFile: New file path 
     *  Call the column: 
     *      string OrignFile = Server.MapPath("Default2.aspx");  
     *      string NewFile = Server.MapPath("Default3.aspx");
     *      DotNet.Utilities.FileOperate.FileCoppy(OrignFile, NewFile);
    *****************************************/
    /// <summary>
    ///  Copy files 
    /// </summary>
    /// <param name="OrignFile"> The original file </param>
    /// <param name="NewFile"> New file path </param>
    public static void FileCoppy(string OrignFile, string NewFile)
    {
      File.Copy(OrignFile, NewFile, true);
    }
    #endregion
    #region  Delete the file 
    /****************************************
     *  Function name: FileDel
     *  Function description: Delete file 
     *  ginseng    The number: Path: The file path 
     *  Call the column: 
     *      string Path = Server.MapPath("Default3.aspx");  
     *      DotNet.Utilities.FileOperate.FileDel(Path);
    *****************************************/
    /// <summary>
    ///  Delete the file 
    /// </summary>
    /// <param name="Path"> The path </param>
    public static void FileDel(string Path)
    {
      File.Delete(Path);
    }
    #endregion
    #region  Move files 
    /****************************************
     *  Function name: FileMove
     *  Function description: Move file 
     *  ginseng    The number: OrignFile: The original path ,NewFile: New file path 
     *  Call the column: 
     *      string OrignFile = Server.MapPath("../ instructions .txt");  
     *      string NewFile = Server.MapPath("../../ instructions .txt");
     *      DotNet.Utilities.FileOperate.FileMove(OrignFile, NewFile);
    *****************************************/
    /// <summary>
    ///  Move files 
    /// </summary>
    /// <param name="OrignFile"> The original path </param>
    /// <param name="NewFile"> A new path </param>
    public static void FileMove(string OrignFile, string NewFile)
    {
      File.Move(OrignFile, NewFile);
    }
    #endregion
    #region  Create a directory under the current directory 
    /****************************************
     *  Function name: FolderCreate
     *  Create a directory under the current directory 
     *  ginseng    The number: OrignFolder: In the current directory ,NewFloder: A new directory 
     *  Call the column: 
     *      string OrignFolder = Server.MapPath("test/");  
     *      string NewFloder = "new";
     *      DotNet.Utilities.FileOperate.FolderCreate(OrignFolder, NewFloder);
    *****************************************/
    /// <summary>
    ///  Create a directory under the current directory 
    /// </summary>
    /// <param name="OrignFolder"> In the current directory </param>
    /// <param name="NewFloder"> A new directory </param>
    public static void FolderCreate(string OrignFolder, string NewFloder)
    {
      Directory.SetCurrentDirectory(OrignFolder);
      Directory.CreateDirectory(NewFloder);
    }
    /// <summary>
    ///  Create folder 
    /// </summary>
    /// <param name="Path"></param>
    public static void FolderCreate(string Path)
    {
      //  Determine if the target directory exists or if it does not, create it 
      if (!Directory.Exists(Path))
        Directory.CreateDirectory(Path);
    }
    #endregion
    #region  Create a directory 
    public static void FileCreate(string Path)
    {
      FileInfo CreateFile = new FileInfo(Path); // Create a file 
      if (!CreateFile.Exists)
      {
        FileStream FS = CreateFile.Create();
        FS.Close();
      }
    }
    #endregion
    #region  Delete folder directories and files recursively 
    /****************************************
     *  Function name: DeleteFolder
     *  Delete folder directories and files recursively 
     *  ginseng    The number: dir: Folder path 
     *  Call the column: 
     *      string dir = Server.MapPath("test/"); 
     *      DotNet.Utilities.FileOperate.DeleteFolder(dir);   
    *****************************************/
    /// <summary>
    ///  Delete folder directories and files recursively 
    /// </summary>
    /// <param name="dir"></param> 
    /// <returns></returns>
    public static void DeleteFolder(string dir)
    {
      if (Directory.Exists(dir)) // If this folder exists delete it 
      {
        foreach (string d in Directory.GetFileSystemEntries(dir))
        {
          if (File.Exists(d))
            File.Delete(d); // Just delete the files             
          else
            DeleteFolder(d); // Delete subfolders recursively 
        }
        Directory.Delete(dir, true); // Delete the empty folder         
      }
    }
    #endregion
    #region  Specifies everything under the folder copy Go under the target folder   An error will be reported if the target folder is read-only. 
    /****************************************
     *  Function name: CopyDir
     *  Description: Everything under the folder will be specified copy Go under the target folder   An error will be reported if the target folder is read-only. 
     *  ginseng    The number: srcPath: The original path ,aimPath: Target folder 
     *  Call the column: 
     *      string srcPath = Server.MapPath("test/"); 
     *      string aimPath = Server.MapPath("test1/");
     *      DotNet.Utilities.FileOperate.CopyDir(srcPath,aimPath); 
    *****************************************/
    /// <summary>
    ///  Specify everything under the folder copy Go under the target folder 
    /// </summary>
    /// <param name="srcPath"> The original path </param>
    /// <param name="aimPath"> Target folder </param>
    public static void CopyDir(string srcPath, string aimPath)
    {
      try
      {
        //  Check whether the target directory ends with a directory segmentation character or if not, add it 
        if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
          aimPath += Path.DirectorySeparatorChar;
        //  Determine if the target directory exists or if it does not, create it 
        if (!Directory.Exists(aimPath))
          Directory.CreateDirectory(aimPath);
        //  Gets the list of files in the source directory containing the files and directory paths 1 An array 
        // If you point to copy The file under the target file does not contain a directory using the following method 
        //string[] fileList = Directory.GetFiles(srcPath);
        string[] fileList = Directory.GetFileSystemEntries(srcPath);
        // Traverse all files and directories 
        foreach (string file in fileList)
        {
          // I'm going to treat it as a directory and recurse if it exists Copy The files below this directory 
          if (Directory.Exists(file))
            CopyDir(file, aimPath + Path.GetFileName(file));
          // Otherwise directly Copy file 
          else
            File.Copy(file, aimPath + Path.GetFileName(file), true);
        }
      }
      catch (Exception ee)
      {
        throw new Exception(ee.ToString());
      }
    }
    #endregion
    #region  Gets all subdirectories and files under the specified folder ( The tree )
    /****************************************
     *  Function name: GetFoldAll(string Path)
     *  Get all subdirectories and files under the specified folder ( The tree )
     *  ginseng    The number: Path: Detailed path 
     *  Call the column: 
     *      string strDirlist = Server.MapPath("templates");   
     *      this.Literal1.Text = DotNet.Utilities.FileOperate.GetFoldAll(strDirlist); 
    *****************************************/
    /// <summary>
    ///  Gets all subdirectories and files under the specified folder 
    /// </summary>
    /// <param name="Path"> Detailed path </param>
    public static string GetFoldAll(string Path)
    {
      string str = "";
      DirectoryInfo thisOne = new DirectoryInfo(Path);
      str = ListTreeShow(thisOne, 0, str);
      return str;
    }
    /// <summary>
    ///  Gets all subdirectories and file functions under the specified folder 
    /// </summary>
    /// <param name="theDir"> The specified directory </param>
    /// <param name="nLevel"> Default start value , A call ,1 As for the 0</param>
    /// <param name="Rn"> An incoming value used for superposition ,1 A null </param>
    /// <returns></returns>
    public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn)// Recursive directory   file 
    {
      DirectoryInfo[] subDirectories = theDir.GetDirectories();// To get the directory 
      foreach (DirectoryInfo dirinfo in subDirectories)
      {
        if (nLevel == 0)
        {
          Rn += " ├ ";
        }
        else
        {
          string _s = "";
          for (int i = 1; i <= nLevel; i++)
          {
            _s += " │ &nbsp;";
          }
          Rn += _s + " ├ ";
        }
        Rn += "<b>" + dirinfo.Name.ToString() + "</b><br />";
        FileInfo[] fileInfo = dirinfo.GetFiles();  // Files in the directory 
        foreach (FileInfo fInfo in fileInfo)
        {
          if (nLevel == 0)
          {
            Rn += " │ &nbsp; ├ ";
          }
          else
          {
            string _f = "";
            for (int i = 1; i <= nLevel; i++)
            {
              _f += " │ &nbsp;";
            }
            Rn += _f + " │ &nbsp; ├ ";
          }
          Rn += fInfo.Name.ToString() + " <br />";
        }
        Rn = ListTreeShow(dirinfo, nLevel + 1, Rn);
 
      }
      return Rn;
    }
 
    /****************************************
     *  Function name: GetFoldAll(string Path)
     *  Get all subdirectories and files under the specified folder ( A drop-down box )
     *  ginseng    The number: Path: Detailed path 
     *  Call the column: 
     *      string strDirlist = Server.MapPath("templates");   
     *      this.Literal2.Text = DotNet.Utilities.FileOperate.GetFoldAll(strDirlist,"tpl","");
    *****************************************/
    /// <summary>
    ///  Gets all subdirectories and files under the specified folder ( A drop-down box )
    /// </summary>
    /// <param name="Path"> Detailed path </param>
    ///<param name="DropName"> Name of the drop-down list </param>
    ///<param name="tplPath"> Choose the template name by default </param>
    public static string GetFoldAll(string Path, string DropName, string tplPath)
    {
      string strDrop = "<select name=\"" + DropName + "\" id=\"" + DropName + "\"><option value=\"\">-- Please select the detailed template --</option>";
      string str = "";
      DirectoryInfo thisOne = new DirectoryInfo(Path);
      str = ListTreeShow(thisOne, 0, str, tplPath);
      return strDrop + str + "</select>";
    }
    /// <summary>
    ///  Gets all subdirectories and file functions under the specified folder 
    /// </summary>
    /// <param name="theDir"> The specified directory </param>
    /// <param name="nLevel"> Default start value , A call ,1 As for the 0</param>
    /// <param name="Rn"> An incoming value used for superposition ,1 A null </param>
    /// <param name="tplPath"> Choose the template name by default </param>
    /// <returns></returns>
    public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn, string tplPath)// Recursive directory   file 
    {
      DirectoryInfo[] subDirectories = theDir.GetDirectories();// To get the directory 
      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 += " │ &nbsp;";
          }
          Rn += _s + " ┣ ";
        }
        Rn += "" + dirinfo.Name.ToString() + "</option>";
 
        FileInfo[] fileInfo = dirinfo.GetFiles();  // Files in the directory 
        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 += " │ &nbsp; ├ ";
          }
          else
          {
            string _f = "";
            for (int i = 1; i <= nLevel; i++)
            {
              _f += " │ &nbsp;";
            }
            Rn += _f + " │ &nbsp; ├ ";
          }
          Rn += fInfo.Name.ToString() + "</option>";
        }
        Rn = ListTreeShow(dirinfo, nLevel + 1, Rn, tplPath);
 
      }
      return Rn;
    }
    #endregion
    #region  Get folder size 
    /****************************************
     *  Function name: GetDirectoryLength(string dirPath)
     *  Function description: Get folder size 
     *  ginseng    The number: dirPath: Folder detail path 
     *  Call the column: 
     *      string Path = Server.MapPath("templates");
     *      Response.Write(DotNet.Utilities.FileOperate.GetDirectoryLength(Path));   
    *****************************************/
    /// <summary>
    ///  Get folder size 
    /// </summary>
    /// <param name="dirPath"> Folder path </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  Gets the specified file details properties 
    /****************************************
     *  Function name: GetFileAttibe(string filePath)
     *  Function description: Gets specified file details properties 
     *  ginseng    The number: filePath: File detail path 
     *  Call the column: 
     *      string file = Server.MapPath("robots.txt"); 
     *      Response.Write(DotNet.Utilities.FileOperate.GetFileAttibe(file));    
    *****************************************/
    /// <summary>
    ///  Gets the specified file details properties 
    /// </summary>
    /// <param name="filePath"> File detail path </param>
    /// <returns></returns>
    public static string GetFileAttibe(string filePath)
    {
      string str = "";
      System.IO.FileInfo objFI = new System.IO.FileInfo(filePath);
      str += " Detailed path :" + objFI.FullName + "<br> The file name :" + objFI.Name + "<br> The length of the file :" + objFI.Length.ToString() + " byte <br> Creation time " + objFI.CreationTime.ToString() + "<br> Last visit time :" + objFI.LastAccessTime.ToString() + "<br> Modify the time :" + objFI.LastWriteTime.ToString() + "<br> directory :" + objFI.DirectoryName + "<br> extension :" + objFI.Extension;
      return str;
    }
    #endregion
  }
}

Hopefully this article has helped you with your C# programming.


Related articles: