SoFunction
Updated on 2025-03-04

C# Commonly Used Directory File Operation Class Example

This article describes the commonly used directory file operation classes in C#. Share it for your reference. The specific analysis is as follows:

This c# class encapsulates commonly used directory operations, including listing files in the directory, detecting whether the directory exists, obtaining a file list in the directory, detecting whether the directory is empty, finding files in the directory, and other functions:

using System;
using ;
using ;
namespace 
{
  /// <summary>
  /// File operation folder  /// </summary>
  public static class DirFile
  {
    #region Detection of the existence of a specified directory    /// <summary>
    /// Detect whether the specified directory exists    /// </summary>
    /// <param name="directoryPath">Absolute path to directory</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static bool IsExistDirectory(string directoryPath)
    {
      return (directoryPath);
    }
    #endregion
    #region Detection whether the specified file exists, and if it exists, it returns true    /// &lt;summary&gt;
    /// Detect whether the specified file exists, and returns true if it exists.    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static bool IsExistFile(string filePath)
    {
      return (filePath);
    }
    #endregion
    #region Gets the list of files in the specified directory    /// &lt;summary&gt;
    /// Get a list of all files in the specified directory    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    public static string[] GetFileNames(string directoryPath)
    {
      // If the directory does not exist, an exception is thrown      if (!IsExistDirectory(directoryPath))
      {
        throw new FileNotFoundException();
      }
      //Get the file list      return (directoryPath);
    }
    #endregion
    #region Gets a list of all subdirectories in the specified directory. To search for a nested subdirectories list, use the overloaded method.    /// &lt;summary&gt;
    /// Get a list of all subdirectories in the specified directory. To search for a nested subdirectories list, use the overloaded method.    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    public static string[] GetDirectories(string directoryPath)
    {
      try
      {
        return (directoryPath);
      }
      catch (IOException ex)
      {
        throw ex;
      }
    }
    #endregion
    #region Gets a list of all files in the specified directory and subdirectories    /// &lt;summary&gt;
    /// Get a list of all files in the specified directory and subdirectories    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    /// <param name="searchPattern">Mode string, "*" represents 0 or N characters, "?" represents 1 character.    /// Example: "Log*.xml" means searching for all Xml files starting with Log.  </param>    /// <param name="isSearchChild">Whether to search for subdirectories</param>    public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
    {
      // If the directory does not exist, an exception is thrown      if (!IsExistDirectory(directoryPath))
      {
        throw new FileNotFoundException();
      }
      try
      {
        if (isSearchChild)
        {
          return (directoryPath, searchPattern, );
        }
        else
        {
          return (directoryPath, searchPattern, );
        }
      }
      catch (IOException ex)
      {
        throw ex;
      }
    }
    #endregion
    #region Detects whether the specified directory is empty    /// &lt;summary&gt;
    /// Detect whether the specified directory is empty    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    public static bool IsEmptyDirectory(string directoryPath)
    {
      try
      {
        //Judge whether there is a file        string[] fileNames = GetFileNames(directoryPath);
        if ( &gt; 0)
        {
          return false;
        }
        //Judge whether there is a folder        string[] directoryNames = GetDirectories(directoryPath);
        if ( &gt; 0)
        {
          return false;
        }
        return true;
      }
      catch
      {
        //Logs are recorded here        //(, );
        return true;
      }
    }
    #endregion
    #region Detects whether the specified file exists in the specified directory    /// &lt;summary&gt;
    /// Detect whether the specified file exists in the specified directory. To search for subdirectories, use the overloaded method.    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    /// <param name="searchPattern">Mode string, "*" represents 0 or N characters, "?" represents 1 character.    /// Example: "Log*.xml" means searching for all Xml files starting with Log.  </param>    public static bool Contains(string directoryPath, string searchPattern)
    {
      try
      {
        //Get the specified file list        string[] fileNames = GetFileNames(directoryPath, searchPattern, false);
        //Judge whether the specified file exists        if ( == 0)
        {
          return false;
        }
        else
        {
          return true;
        }
      }
      catch (Exception ex)
      {
        throw new Exception();
        //(, );
      }
    }
    /// &lt;summary&gt;
    /// Detect whether the specified file exists in the specified directory    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    /// <param name="searchPattern">Mode string, "*" represents 0 or N characters, "?" represents 1 character.    /// Example: "Log*.xml" means searching for all Xml files starting with Log.  </param>    /// <param name="isSearchChild">Whether to search for subdirectories</param>    public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)
    {
      try
      {
        //Get the specified file list        string[] fileNames = GetFileNames(directoryPath, searchPattern, true);
        //Judge whether the specified file exists        if ( == 0)
        {
          return false;
        }
        else
        {
          return true;
        }
      }
      catch (Exception ex)
      {
        throw new Exception();
        //(, );
      }
    }
    #endregion
    #region Create directory    /// &lt;summary&gt;
    /// Create a directory    /// &lt;/summary&gt;
    /// <param name="dir">The directory path to create includes the directory name</param>    public static void CreateDir(string dir)
    {
      if ( == 0) return;
      if (!( + "\\" + dir))
        ( + "\\" + dir);
    }
    #endregion
    #region Delete Directory    /// &lt;summary&gt;
    /// Delete the directory    /// &lt;/summary&gt;
    /// <param name="dir">Dir path and name to delete</param>    public static void DeleteDir(string dir)
    {
      if ( == 0) return;
      if (( + "\\" + dir))
        ( + "\\" + dir);
    }
    #endregion
    #region Delete file    /// &lt;summary&gt;
    /// Delete the file    /// &lt;/summary&gt;
    /// <param name="file">The path and name of the file to be deleted</param>    public static void DeleteFile(string file)
    {
      if (( + file))
        ( + file);
    }
    #endregion
    #region Create a file    /// &lt;summary&gt;
    /// Create a file    /// &lt;/summary&gt;
    /// <param name="dir">File name with suffix</param>    /// <param name="pagestr">File content</param>    public static void CreateFile(string dir, string pagestr)
    {
      dir = ("/", "\\");
      if (("\\") &gt; -1)
        CreateDir((0, ("\\")));
       sw = new ( + "\\" + dir, false, ("GB2312"));
      (pagestr);
      ();
    }
    #endregion
    #region Move file (clip-paste)    /// &lt;summary&gt;
    /// Move files (clip-paste)    /// &lt;/summary&gt;
    /// <param name="dir1">Path and full name of the file to be moved (including suffix)</param>    /// <param name="dir2">Move the file to a new location and specify the new file name</param>    public static void MoveFile(string dir1, string dir2)
    {
      dir1 = ("/", "\\");
      dir2 = ("/", "\\");
      if (( + "\\" + dir1))
        ( + "\\" + dir1,  + "\\" + dir2);
    }
    #endregion
    #region Copy files    /// &lt;summary&gt;
    /// Copy the file    /// &lt;/summary&gt;
    /// <param name="dir1">The path to the file to be copied has full name (including suffix)</param>    /// <param name="dir2">Target location and specify a new file name</param>    public static void CopyFile(string dir1, string dir2)
    {
      dir1 = ("/", "\\");
      dir2 = ("/", "\\");
      if (( + "\\" + dir1))
      {
        ( + "\\" + dir1,  + "\\" + dir2, true);
      }
    }
    #endregion
    #region Get directory name/format:yyyyMMdd or HHmmssff    /// &lt;summary&gt;
    /// Get the directory name yyyyMMdd according to the time    /// &lt;/summary&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static string GetDateDir()
    {
      return ("yyyyMMdd");
    }
    /// &lt;summary&gt;
    /// Get the file name HHmmssff according to the time    /// &lt;/summary&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static string GetDateFile()
    {
      return ("HHmmssff");
    }
    #endregion
    #region Copy folder    /// &lt;summary&gt;
    /// Copy folder (recursive)    /// &lt;/summary&gt;
    /// <param name="varFromDirectory">Source folder path</param>    /// <param name="varToDirectory">Target folder path</param>    public static void CopyFolder(string varFromDirectory, string varToDirectory)
    {
      (varToDirectory);
      if (!(varFromDirectory)) return;
      string[] directories = (varFromDirectory);
      if ( &gt; 0)
      {
        foreach (string d in directories)
        {
          CopyFolder(d, varToDirectory + (("\\")));
        }
      }
      string[] files = (varFromDirectory);
      if ( &gt; 0)
      {
        foreach (string s in files)
        {
          (s, varToDirectory + (("\\")), true);
        }
      }
    }
    #endregion
    #region Check the file, create it if the file does not exist    /// &lt;summary&gt;
    /// Check the file, create it if the file does not exist    /// &lt;/summary&gt;
    /// <param name="FilePath">Path, including file name</param>    public static void ExistsFile(string FilePath)
    {
      //if(!(FilePath))  
      //(FilePath);  
      //The above writing method will cause an error. Please refer to the details below...      if (!(FilePath))
      {
        FileStream fs = (FilePath);
        ();
      }
    }
    #endregion
    #region Delete files in other folders corresponding to the specified folder    /// &lt;summary&gt;
    /// Delete files in other folders corresponding to the specified folder    /// &lt;/summary&gt;
    /// <param name="varFromDirectory">Specify folder path</param>    /// <param name="varToDirectory">correspond to other folder paths</param>    public static void DeleteFolderFiles(string varFromDirectory, string varToDirectory)
    {
      (varToDirectory);
      if (!(varFromDirectory)) return;
      string[] directories = (varFromDirectory);
      if ( &gt; 0)
      {
        foreach (string d in directories)
        {
          DeleteFolderFiles(d, varToDirectory + (("\\")));
        }
      }
 
      string[] files = (varFromDirectory);
      if ( &gt; 0)
      {
        foreach (string s in files)
        {
          (varToDirectory + (("\\")));
        }
      }
    }
    #endregion
    #region Get file name (including extension) from the absolute path of the file    /// &lt;summary&gt;
    /// Get the file name (including extension) from the absolute path of the file    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static string GetFileName(string filePath)
    {
      //Get the file name      FileInfo fi = new FileInfo(filePath);
      return ;
    }
    #endregion
    /// &lt;summary&gt;
    /// Copy file reference method, reference on the page    /// &lt;/summary&gt;
    /// <param name="cDir">New path</param>    /// <param name="TempId">Template engine replacement number</param>    public static void CopyFiles(string cDir, string TempId)
    {
      //if (( + "\\Controls"))
      //{
      //  string TempStr = ;
      //  StreamWriter sw;
      //  if (( + "\\Controls\\"))
      //  {
      //    TempStr = ( + "\\Controls\\");
      //    TempStr = ("{$ChannelId$}", TempId);
      //    sw = new StreamWriter( + "\\" + cDir + "\\", false, ("GB2312"));
      //    (TempStr);
      //    ();
      //  }
      //  if (( + "\\Controls\\"))
      //  {
      //    TempStr = ( + "\\Controls\\");
      //    TempStr = ("{$ChannelId$}", TempId);
      //    sw = new StreamWriter( + "\\" + cDir + "\\", false, ("GB2312"));
      //    (TempStr);
      //    ();
      //  }
      //  if (( + "\\Controls\\"))
      //  {
      //    TempStr = ( + "\\Controls\\");
      //    TempStr = ("{$ChannelId$}", TempId);
      //    sw = new StreamWriter( + "\\" + cDir + "\\", false, ("GB2312"));
      //    (TempStr);
      //    ();
      //  }
      //  if (( + "\\Controls\\"))
      //  {
      //    TempStr = ( + "\\Controls\\");
      //    TempStr = ("{$ChannelId$}", TempId);
      //    sw = new StreamWriter( + "\\" + cDir + "\\", false, ("GB2312"));
      //    (TempStr);
      //    ();
      //  }
      //  if (( + "\\Controls\\"))
      //  {
      //    TempStr = ( + "\\Controls\\");
      //    TempStr = ("{$ChannelId$}", TempId);
      //    sw = new StreamWriter( + "\\" + cDir + "\\", false, ("GB2312"));
      //    (TempStr);
      //    ();
      //  }
      //  if (( + "\\Controls\\"))
      //  {
      //    TempStr = ( + "\\Controls\\");
      //    TempStr = ("{$ChannelId$}", TempId);
      //    sw = new StreamWriter( + "\\" + cDir + "\\", false, ("GB2312"));
      //    (TempStr);
      //    ();
      //  }
      //  if (( + "\\Controls\\"))
      //  {
      //    TempStr = ( + "\\Controls\\");
      //    TempStr = ("{$ChannelId$}", TempId);
      //    sw = new StreamWriter( + "\\" + cDir + "\\", false, ("GB2312"));
      //    (TempStr);
      //    ();
      //  }
      //}
    }
 
    #region Create a directory    /// &lt;summary&gt;
    /// Create a directory    /// &lt;/summary&gt;
    /// <param name="directoryPath">Absolute path to directory</param>    public static void CreateDirectory(string directoryPath)
    {
      //Create the directory if it does not exist      if (!IsExistDirectory(directoryPath))
      {
        (directoryPath);
      }
    }
    #endregion
    #region Create a file    /// &lt;summary&gt;
    /// Create a file.    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static void CreateFile(string filePath)
    {
      try
      {
        //Create the file if it does not exist        if (!IsExistFile(filePath))
        {
          //Create a FileInfo object          FileInfo file = new FileInfo(filePath);
          //Create a file          FileStream fs = ();
          //Close the file stream          ();
        }
      }
      catch (Exception ex)
      {
        //(, );
        throw ex;
      }
    }
    /// &lt;summary&gt;
    /// Create a file and write the byte stream to the file.    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    /// <param name="buffer">Binary stream data</param>    public static void CreateFile(string filePath, byte[] buffer)
    {
      try
      {
        //Create the file if it does not exist        if (!IsExistFile(filePath))
        {
          //Create a FileInfo object          FileInfo file = new FileInfo(filePath);
          //Create a file          FileStream fs = ();
          //Write to binary stream          (buffer, 0, );
          //Close the file stream          ();
        }
      }
      catch (Exception ex)
      {
        //(, );
        throw ex;
      }
    }
    #endregion
    #region Gets the number of lines of a text file    /// &lt;summary&gt;
    /// Get the number of lines of the text file    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static int GetLineCount(string filePath)
    {
      //Read each line of the text file into an array of strings      string[] rows = (filePath);
      //Return the number of rows      return ;
    }
    #endregion
    #region Gets the length of a file    /// &lt;summary&gt;
    /// Get the length of a file, unit of Byte    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static int GetFileSize(string filePath)
    {
      //Create a file object      FileInfo fi = new FileInfo(filePath);
      //Get the file size      return (int);
    }
    #endregion
    #region Gets a list of subdirectories in the specified directory    /// &lt;summary&gt;
    /// Get a list of all subdirectories in the specified directory and subdirectories    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    /// <param name="searchPattern">Mode string, "*" represents 0 or N characters, "?" represents 1 character.    /// Example: "Log*.xml" means searching for all Xml files starting with Log.  </param>    /// <param name="isSearchChild">Whether to search for subdirectories</param>    public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
    {
      try
      {
        if (isSearchChild)
        {
          return (directoryPath, searchPattern, );
        }
        else
        {
          return (directoryPath, searchPattern, );
        }
      }
      catch (IOException ex)
      {
        throw ex;
      }
    }
    #endregion
    #region Write content to a text file    /// &lt;summary&gt;
    /// Write content to a text file    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    /// <param name="text">Written content</param>    /// <param name="encoding">Encoding</param>    public static void WriteText(string filePath, string text, Encoding encoding)
    {
      //Write content to the file      (filePath, text, encoding);
    }
    #endregion
    #region Add content to the end of the text file    /// &lt;summary&gt;
    /// Add content to the end of the text file    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    /// <param name="content">Written content</param>    public static void AppendText(string filePath, string content)
    {
      (filePath, content);
    }
    #endregion
    #region Copy the contents of an existing file to a new file    /// &lt;summary&gt;
    /// Copy the contents of the source file into the target file    /// &lt;/summary&gt;
    /// <param name="sourceFilePath">Absolute path to source file</param>    /// <param name="destFilePath">Absolute path to the target file</param>    public static void Copy(string sourceFilePath, string destFilePath)
    {
      (sourceFilePath, destFilePath, true);
    }
    #endregion
    #region Move the file to the specified directory    /// &lt;summary&gt;
    /// Move the file to the specified directory    /// &lt;/summary&gt;
    /// <param name="sourceFilePath">Absolute path to source files that need to be moved</param>    /// <param name="descDirectoryPath">Absolute path to the directory moved to</param>    public static void Move(string sourceFilePath, string descDirectoryPath)
    {
      //Get the name of the source file      string sourceFileName = GetFileName(sourceFilePath);
      if (IsExistDirectory(descDirectoryPath))
      {
        //If there is a file with the same name in the target, delete it        if (IsExistFile(descDirectoryPath + "\\" + sourceFileName))
        {
          DeleteFile(descDirectoryPath + "\\" + sourceFileName);
        }
        //Move the file to the specified directory        (sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
      }
    }
    #endregion
 
    #region Get file name from the absolute path of the file (excluding extension)    /// &lt;summary&gt;
    /// Get the file name from the absolute path of the file (excluding the extension)    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static string GetFileNameNoExtension(string filePath)
    {
      //Get the file name      FileInfo fi = new FileInfo(filePath);
      return ('.')[0];
    }
    #endregion
    #region Get extension from the absolute path of the file    /// &lt;summary&gt;
    /// Get the extension from the absolute path of the file    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static string GetExtension(string filePath)
    {
      //Get the file name      FileInfo fi = new FileInfo(filePath);
      return ;
    }
    #endregion
    #region Clear the specified directory    /// &lt;summary&gt;
    /// Clear all files and subdirectories in the specified directory, but the directory is still saved.    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    public static void ClearDirectory(string directoryPath)
    {
      if (IsExistDirectory(directoryPath))
      {
        //Delete all files in the directory        string[] fileNames = GetFileNames(directoryPath);
        for (int i = 0; i &lt; ; i++)
        {
          DeleteFile(fileNames[i]);
        }
        //Delete all subdirectories in the directory        string[] directoryNames = GetDirectories(directoryPath);
        for (int i = 0; i &lt; ; i++)
        {
          DeleteDirectory(directoryNames[i]);
        }
      }
    }
    #endregion
    #region Clear file content    /// &lt;summary&gt;
    /// Clear the file contents    /// &lt;/summary&gt;
    /// <param name="filePath">Absolute path to file</param>    public static void ClearFile(string filePath)
    {
      //Delete the file      (filePath);
      //Recreate the file      CreateFile(filePath);
    }
    #endregion
    #region Delete the specified directory    /// &lt;summary&gt;
    /// Delete the specified directory and all its subdirectories    /// &lt;/summary&gt;
    /// <param name="directoryPath">Specify the absolute path to the directory</param>    public static void DeleteDirectory(string directoryPath)
    {
      if (IsExistDirectory(directoryPath))
      {
        (directoryPath, true);
      }
    }
    #endregion
  }
}

I hope this article will be helpful to everyone's C# programming.