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> /// <returns></returns> public static bool IsExistDirectory(string directoryPath) { return (directoryPath); } #endregion #region Detection whether the specified file exists, and if it exists, it returns true /// <summary> /// Detect whether the specified file exists, and returns true if it exists. /// </summary> /// <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 /// <summary> /// Get a list of all files in the specified directory /// </summary> /// <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. /// <summary> /// Get a list of all subdirectories in the specified directory. To search for a nested subdirectories list, use the overloaded method. /// </summary> /// <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 /// <summary> /// Get a list of all files in the specified directory and subdirectories /// </summary> /// <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 /// <summary> /// Detect whether the specified directory is empty /// </summary> /// <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 ( > 0) { return false; } //Judge whether there is a folder string[] directoryNames = GetDirectories(directoryPath); if ( > 0) { return false; } return true; } catch { //Logs are recorded here //(, ); return true; } } #endregion #region Detects whether the specified file exists in the specified directory /// <summary> /// Detect whether the specified file exists in the specified directory. To search for subdirectories, use the overloaded method. /// </summary> /// <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(); //(, ); } } /// <summary> /// Detect whether the specified file exists in the specified directory /// </summary> /// <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 /// <summary> /// Create a directory /// </summary> /// <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 /// <summary> /// Delete the directory /// </summary> /// <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 /// <summary> /// Delete the file /// </summary> /// <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 /// <summary> /// Create a file /// </summary> /// <param name="dir">File name with suffix</param> /// <param name="pagestr">File content</param> public static void CreateFile(string dir, string pagestr) { dir = ("/", "\\"); if (("\\") > -1) CreateDir((0, ("\\"))); sw = new ( + "\\" + dir, false, ("GB2312")); (pagestr); (); } #endregion #region Move file (clip-paste) /// <summary> /// Move files (clip-paste) /// </summary> /// <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 /// <summary> /// Copy the file /// </summary> /// <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 /// <summary> /// Get the directory name yyyyMMdd according to the time /// </summary> /// <returns></returns> public static string GetDateDir() { return ("yyyyMMdd"); } /// <summary> /// Get the file name HHmmssff according to the time /// </summary> /// <returns></returns> public static string GetDateFile() { return ("HHmmssff"); } #endregion #region Copy folder /// <summary> /// Copy folder (recursive) /// </summary> /// <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 ( > 0) { foreach (string d in directories) { CopyFolder(d, varToDirectory + (("\\"))); } } string[] files = (varFromDirectory); if ( > 0) { foreach (string s in files) { (s, varToDirectory + (("\\")), true); } } } #endregion #region Check the file, create it if the file does not exist /// <summary> /// Check the file, create it if the file does not exist /// </summary> /// <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 /// <summary> /// Delete files in other folders corresponding to the specified folder /// </summary> /// <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 ( > 0) { foreach (string d in directories) { DeleteFolderFiles(d, varToDirectory + (("\\"))); } } string[] files = (varFromDirectory); if ( > 0) { foreach (string s in files) { (varToDirectory + (("\\"))); } } } #endregion #region Get file name (including extension) 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 to file</param> public static string GetFileName(string filePath) { //Get the file name FileInfo fi = new FileInfo(filePath); return ; } #endregion /// <summary> /// Copy file reference method, reference on the page /// </summary> /// <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 /// <summary> /// Create a directory /// </summary> /// <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 /// <summary> /// Create a file. /// </summary> /// <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; } } /// <summary> /// Create a file and write the byte stream to the file. /// </summary> /// <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 /// <summary> /// Get the number of lines of the text file /// </summary> /// <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 /// <summary> /// Get the length of a file, unit of Byte /// </summary> /// <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 /// <summary> /// Get a list of all subdirectories in the specified directory and subdirectories /// </summary> /// <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 /// <summary> /// Write content to a text file /// </summary> /// <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 /// <summary> /// Add content to the end of the text file /// </summary> /// <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 /// <summary> /// Copy the contents of the source file into the target file /// </summary> /// <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 /// <summary> /// Move the file to the specified directory /// </summary> /// <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) /// <summary> /// Get the file name from the absolute path of the file (excluding the extension) /// </summary> /// <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 /// <summary> /// Get the extension from the absolute path of the file /// </summary> /// <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 /// <summary> /// Clear all files and subdirectories in the specified directory, but the directory is still saved. /// </summary> /// <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 < ; i++) { DeleteFile(fileNames[i]); } //Delete all subdirectories in the directory string[] directoryNames = GetDirectories(directoryPath); for (int i = 0; i < ; i++) { DeleteDirectory(directoryNames[i]); } } } #endregion #region Clear file content /// <summary> /// Clear the file contents /// </summary> /// <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 /// <summary> /// Delete the specified directory and all its subdirectories /// </summary> /// <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.