C# Implementing File and Directory Operation

The most complete file and directory operations

Sources of information are not easy.

 

1. Detecting the existence of a specified directory

public static class DirFile
 {
  /// <summary>
  /// Detecting the existence of a specified directory
  /// </summary>
  /// <param name="directoryPath">absolute path of directory </param>
  /// <returns></returns>
  public static bool IsExistDirectory(string directoryPath)
  {
   return Directory.Exists(directoryPath);
  }

 

2. Get a list of all files in the specified directory

  /// <summary>
  /// Gets a list of all files in the specified directory
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified 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 a list of files
   return Directory.GetFiles(directoryPath);
  }

 

3. Get a list of all subdirectories in the specified directory

  /// <summary>
  /// Gets a list of all subdirectories in the specified directory. To search for nested subdirectory lists, use the overload method
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified directory </param>
  public static string[] GetDirectories(string directoryPath)
  {
   try
   {
    return Directory.GetDirectories(directoryPath);
   }
   catch (IOException ex)
   {
    throw ex;
   }
  }

 

4. Get a list of all files in the specified directory and subdirectory

  /// <summary>
  /// Gets a list of all files in the specified directory and subdirectory
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified directory </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 Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
    }
    else
    {
     return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
    }
   }
   catch (IOException ex)
   {
    throw ex;
   }
  }

5. Detecting whether the specified directory is empty

  /// <summary>
  /// Check whether the specified directory is empty
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified directory </param>
  public static bool IsEmptyDirectory(string directoryPath)
  {
   try
   {
    //Determine whether a document exists
    string[] fileNames = GetFileNames(directoryPath);
    if (fileNames.Length > 0)
    {
     return false;
    }
    //Determine whether a folder exists
    string[] directoryNames = GetDirectories(directoryPath);
    if (directoryNames.Length > 0)
    {
     return false;
    }
    return true;
   }
   catch
   {
    return true;
   }
  }

6. Detect the existence of the specified file in the specified directory

  /// <summary>
  /// Detection of the existence of a specified file in a specified directory
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified directory </param>
  public static bool Contains(string directoryPath, string searchPattern)
  {
   try
   {
    //Gets the specified list of files
    string[] fileNames = GetFileNames(directoryPath, searchPattern, false);
 
    //Determine whether the specified file exists
    if (fileNames.Length == 0)
    {
     return false;
    }
    else
    {
     return true;
    }
   }
   catch (Exception ex)
   {
    throw new Exception(ex.Message);
   }
  }

7. Create directories

  /// <summary>
  /// Create directories
  /// </summary>
  /// <param name="dir">The directory path to be created includes directory name </param>
  public static void CreateDir(string dir)
  {
   if (dir.Length == 0) return;
   if (!Directory.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir))
    Directory.CreateDirectory(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir);
  }

8. Delete directories

  /// <summary>
  /// Delete directories
  /// </summary>
  /// <param name="dir">directory path and name to delete </param>
  public static void DeleteDir(string dir)
  {
   if (dir.Length == 0) return;
   if (Directory.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir))
    Directory.Delete(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir);
  }

9. Delete files

  /// <summary>
  /// Delete files
  /// </summary>
  /// <param name="file">the path and name of the file to be deleted </param>
  public static void DeleteFile(string file)
  {
   if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + file))
    File.Delete(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + file);
  }

10. Create files

  /// <summary>
  /// Create files
  /// </summary>
  /// <param name="dir">File name with suffix </param>
  /// <param name="pagestr">file content </param>
  public static void CreateFile(string dir, string pagestr)
  {
   dir = dir.Replace("/", "\\");
   if (dir.IndexOf("\\") > -1)
    CreateDir(dir.Substring(0, dir.LastIndexOf("\\")));
   System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir, false, System.Text.Encoding.GetEncoding("Opp"));
   sw.Write(pagestr);
   sw.Close();
  }

11. Mobile files

  /// <summary>
  /// Move files (clip-paste)
  /// </summary>
  /// <param name="dir1">the 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 a new file name </param>.
  public static void MoveFile(string dir1, string dir2)
  {
   dir1 = dir1.Replace("/", "\\");
   dir2 = dir2.Replace("/", "\\");
   if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1))
    File.Move(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir2);
  }

12. Replication of documents

  /// <summary>
  /// Copy files
  /// </summary>
  /// <param name="dir1"> The path of the file to be copied has its 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 = dir1.Replace("/", "\\");
   dir2 = dir2.Replace("/", "\\");
   if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1))
   {
    File.Copy(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir2, true);
   }
  }

13. Get directory names by time: YYYY-MM-DD

  /// <summary>
  /// Get the directory name YYYY-MM-DD according to the time
  /// </summary>
  /// <returns></returns>
  public static string GetDateDir()
  {
   return DateTime.Now.ToString("YYYY-MM-DD");
  }

14. File name format based on time: hh-mm-ss-ff

  /// <summary>
  /// get the file name hh-mm-ss-ff according to the time
  /// </summary>
  /// <returns></returns>
  public static string GetDateFile()
  {
   return DateTime.Now.ToString("hh-mm-ss-ff");
  }

15. Copy folders

  /// <summary>
  /// Copy folders
  /// </summary>
  /// <param name="varFromDirectory">source folder path </param>
  /// <param name="varToDirectory">Target folder path </param>
  public static void CopyFolder(string varFromDirectory, string varToDirectory)
  {
   Directory.CreateDirectory(varToDirectory);
   if (!Directory.Exists(varFromDirectory)) return;
   string[] directories = Directory.GetDirectories(varFromDirectory);
   if (directories.Length > 0)
   {
    foreach (string d in directories)
    {
     CopyFolder(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
    }
   }
   string[] files = Directory.GetFiles(varFromDirectory);
   if (files.Length > 0)
   {
    foreach (string s in files)
    {
     File.Copy(s, varToDirectory + s.Substring(s.LastIndexOf("\\")), true);
    }
   }
  }

16. Inspection of documents

  /// <summary>
  /// Check the file and create it if it does not exist 
  /// Create if the file does not exist!
  /// </summary>
  /// <param name="FilePath"> path, including file name </param>
  public static void ExistsFile(string FilePath)
  {
   if (!File.Exists(FilePath))
   {
    FileStream fs = File.Create(FilePath);
    fs.Close();
   }
  }

17. Delete files in specified folders corresponding to other folders

  /// <summary>
  /// Delete files in specified folders corresponding to other folders
  /// </summary>
  /// <param name="varFromDirectory">Specified folder path </param>
  /// <param name="varToDirectory">corresponding to other folder paths </param>
  public static void DeleteFolderFiles(string varFromDirectory, string varToDirectory)
  {
   Directory.CreateDirectory(varToDirectory);
 
   if (!Directory.Exists(varFromDirectory)) return;
 
   string[] directories = Directory.GetDirectories(varFromDirectory);
 
   if (directories.Length > 0)
   {
    foreach (string d in directories)
    {
     DeleteFolderFiles(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
    }
   }
   string[] files = Directory.GetFiles(varFromDirectory);
   if (files.Length > 0)
   {
    foreach (string s in files)
    {
     File.Delete(varToDirectory + s.Substring(s.LastIndexOf("\\")));
    }
   }
  }

18. Get the file name from the absolute path of the file

  /// <summary>
  /// Get the file name (including extension) from the absolute path of the file
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>  
  public static string GetFileName(string filePath)
  {
   //Get the name of the file
   FileInfo fi = new FileInfo(filePath);
   return fi.Name;
  }

19. Create a directory

  /// <summary>
  /// Create a directory
  /// </summary>
  /// <param name="directoryPath">absolute path of directory </param>
  public static void CreateDirectory(string directoryPath)
  {
   //Create a directory if it does not exist
   if (!IsExistDirectory(directoryPath))
   {
    Directory.CreateDirectory(directoryPath);
   }
  }

20. Create a file

  /// <summary>
  /// Create a file
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>
  public static void CreateFile(string filePath)
  {
   try
   {
    //Create a file if it does not exist
    if (!IsExistFile(filePath))
    {
     //Create a FileInfo object
     FileInfo file = new FileInfo(filePath);
 
     //create a file
     FileStream fs = file.Create();
 
     //Close the file stream
     fs.Close();
    }
   }
   catch (Exception ex)
   {
    throw ex;
   }
  }

21. Number of rows to obtain text files

  /// <summary>
  /// Get the number of lines of a text file
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>  
  public static int GetLineCount(string filePath)
  {
   //Read the lines of a text file into an array of strings
   string[] rows = File.ReadAllLines(filePath);
 
   //Number of rows returned
   return rows.Length;
  }

22. Get the length of a file

  /// <summary>
  /// Get the length of a file in Byte
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>  
  public static int GetFileSize(string filePath)
  {
   //Create a file object
   FileInfo fi = new FileInfo(filePath);
 
   //Get the size of the file
   return (int)fi.Length;
  }

23. Gets a list of subdirectories in a specified directory

  /// <summary>
  /// Gets a list of all subdirectories in the specified directory and subdirectory
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified directory </param>
  public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
  {
   try
   {
    if (isSearchChild)
    {
     return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
    }
    else
    {
     return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
    }
   }
   catch (IOException ex)
   {
    throw ex;
   }
  }

24. Write content to a text file

  /// <summary>
  /// Write content to a text file
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>
  /// <param name="text">Written content </param>
  public static void WriteText(string filePath, string text, Encoding encoding)
  {
   //Write content to a file
   File.WriteAllText(filePath, text, encoding);
  }

25. Adding content to the end of a text file

  /// <summary>
  /// Adding content to the end of a text file
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>
  /// <param name="content">Written content</param>
  public static void AppendText(string filePath, string content)
  {
   File.AppendAllText(filePath, content);
  }

26. Copy the contents of existing files to new files

  /// <summary>
  /// Copy the contents of the source file to the target file
  /// </summary>
  /// <param name="sourceFilePath">absolute path of source file </param>
  /// <param name="destFilePath">Absolute path of target file </param>
  public static void Copy(string sourceFilePath, string destFilePath)
  {
   File.Copy(sourceFilePath, destFilePath, true);
  }

27. Move files to a specified directory

  /// <summary>
  /// Move the file to the specified directory
  /// </summary>
  /// <param name="sourceFilePath">Absolute path of source file to be moved </param>
  /// <param name="descDirectoryPath">The 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
    File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
   }
  }

28. Get the file name from the absolute path of the file (no extension included)

  /// <summary>
  /// Get the file name from the absolute path of the file (no extension included)
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>  
  public static string GetFileNameNoExtension(string filePath)
  {
   //Get the name of the file
   FileInfo fi = new FileInfo(filePath);
   return fi.Name.Split('.')[0];
  }

29. Get the extension from the absolute path of the file

  /// <summary>
  /// Get the extension from the absolute path of the file
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>  
  public static string GetExtension(string filePath)
  {
   //Get the name of the file
   FileInfo fi = new FileInfo(filePath);
   return fi.Extension;
  }

30. Clear the designated directory

  /// <summary>
  /// Clear all files and subdirectories in the specified directory, but the directory is still saved
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified 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 < fileNames.Length; i++)
    {
     DeleteFile(fileNames);
    }
 
    //Delete all subdirectories in a directory
    string[] directoryNames = GetDirectories(directoryPath);
    for (int i = 0; i < directoryNames.Length; i++)
    {
     DeleteDirectory(directoryNames);
    }
   }
  }

31. Clearing up the contents of documents

  /// <summary>
  /// Clean up the contents of documents
  /// </summary>
  /// <param name="filePath">Absolute path of file </param>
  public static void ClearFile(string filePath)
  {
   //Delete files
   File.Delete(filePath);
 
   //Recreate the file
   CreateFile(filePath);
  }

32. Delete the specified directory

  /// <summary>
  /// Delete the specified directory and all its subdirectories
  /// </summary>
  /// <param name="directoryPath">Absolute path of specified directory </param>
  public static void DeleteDirectory(string directoryPath)
  {
   if (IsExistDirectory(directoryPath))
   {
    Directory.Delete(directoryPath, true);
   }
  }

In fact, I am afraid of what I will encounter in the future, but it is difficult to solve, so this blog appeared.

Welcome guidance on what went wrong.

Keywords: encoding Mobile

Added by matecocido on Fri, 19 Jul 2019 14:35:35 +0300