C common directory file manipulation class instances
- 2021-01-02 21:58:04
- OfStack
This article gives an example of the common C# directory file action class. Share to everybody for everybody reference. The specific analysis is as follows:
This c# class encapsulates common directory operations, including the ability to list files in a directory, detect if a directory exists, get a list of files in a directory, detect if a directory is empty, find files in a directory, and so on
using System;
using System.Text;
using System.IO;
namespace DotNet.Utilities
{
/// <summary>
/// File operation folder
/// </summary>
public static class DirFile
{
#region Checks if the specified directory exists
/// <summary>
/// Checks if the specified directory exists
/// </summary>
/// <param name="directoryPath"> The absolute path to the directory </param>
/// <returns></returns>
public static bool IsExistDirectory(string directoryPath)
{
return Directory.Exists(directoryPath);
}
#endregion
#region Checks whether the specified file exists , Return if there is true
/// <summary>
/// Checks whether the specified file exists , Returns if it exists true .
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static bool IsExistFile(string filePath)
{
return File.Exists(filePath);
}
#endregion
#region Gets a list of files in the specified directory
/// <summary>
/// Gets a list of all files in the specified directory
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of 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 a list of files
return Directory.GetFiles(directoryPath);
}
#endregion
#region Gets a list of all subdirectories in the specified directory , To search for a list of nested subdirectories , Use overloaded methods .
/// <summary>
/// Gets a list of all subdirectories in the specified directory , To search for a list of nested subdirectories , Use overloaded methods .
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of the directory </param>
public static string[] GetDirectories(string directoryPath)
{
try
{
return Directory.GetDirectories(directoryPath);
}
catch (IOException ex)
{
throw ex;
}
}
#endregion
#region Gets 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"> Specifies the absolute path of the directory </param>
/// <param name="searchPattern"> Pattern string, "*" On behalf of 0 or N A character, "?" On behalf of 1 A character.
/// Example: "Log*.xml" Represents all searches to Log At the beginning of Xml File. </param>
/// <param name="isSearchChild"> Whether to search 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 Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
}
else
{
return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
}
}
catch (IOException ex)
{
throw ex;
}
}
#endregion
#region Checks whether the specified directory is empty
/// <summary>
/// Checks whether the specified directory is empty
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of the directory </param>
public static bool IsEmptyDirectory(string directoryPath)
{
try
{
// Determine if a file exists
string[] fileNames = GetFileNames(directoryPath);
if (fileNames.Length > 0)
{
return false;
}
// Determine if a folder exists
string[] directoryNames = GetDirectories(directoryPath);
if (directoryNames.Length > 0)
{
return false;
}
return true;
}
catch
{
// Log in here
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
return true;
}
}
#endregion
#region Checks whether the specified file exists in the specified directory
/// <summary>
/// Checks whether the specified file exists in the specified directory , To search subdirectories use overloaded methods .
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of the directory </param>
/// <param name="searchPattern"> Pattern string, "*" On behalf of 0 or N A character, "?" On behalf of 1 A character.
/// Example: "Log*.xml" Represents all searches to Log At the beginning of Xml File. </param>
public static bool Contains(string directoryPath, string searchPattern)
{
try
{
// Gets the specified list of files
string[] fileNames = GetFileNames(directoryPath, searchPattern, false);
// Determines whether the specified file exists
if (fileNames.Length == 0)
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
}
}
/// <summary>
/// Checks whether the specified file exists in the specified directory
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of the directory </param>
/// <param name="searchPattern"> Pattern string, "*" On behalf of 0 or N A character, "?" On behalf of 1 A character.
/// Example: "Log*.xml" Represents all searches to Log At the beginning of Xml File. </param>
/// <param name="isSearchChild"> Whether to search subdirectories </param>
public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)
{
try
{
// Gets the specified list of files
string[] fileNames = GetFileNames(directoryPath, searchPattern, true);
// Determines whether the specified file exists
if (fileNames.Length == 0)
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
}
}
#endregion
#region Create a 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 (dir.Length == 0) return;
if (!Directory.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir))
Directory.CreateDirectory(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir);
}
#endregion
#region Delete the directory
/// <summary>
/// Delete the directory
/// </summary>
/// <param name="dir"> The 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);
}
#endregion
#region Delete the file
/// <summary>
/// Delete the file
/// </summary>
/// <param name="file"> The path and name of the file to delete </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);
}
#endregion
#region Create a file
/// <summary>
/// Create a file
/// </summary>
/// <param name="dir"> File names with suffixes </param>
/// <param name="pagestr"> The 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("GB2312"));
sw.Write(pagestr);
sw.Close();
}
#endregion
#region Move files ( Cut and paste -- paste )
/// <summary>
/// Move files ( Cut and paste -- paste )
/// </summary>
/// <param name="dir1"> The path and full name of the file you want to move ( Including the suffix )</param>
/// <param name="dir2"> The file is moved 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);
}
#endregion
#region Copy the file
/// <summary>
/// Copy the file
/// </summary>
/// <param name="dir1"> The path of the file to be copied is already full name ( Including the suffix )</param>
/// <param name="dir2"> The 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);
}
}
#endregion
#region Get the directory name by time / format :yyyyMMdd or HHmmssff
/// <summary>
/// Get the directory name by time yyyyMMdd
/// </summary>
/// <returns></returns>
public static string GetDateDir()
{
return DateTime.Now.ToString("yyyyMMdd");
}
/// <summary>
/// Get the file name by time HHmmssff
/// </summary>
/// <returns></returns>
public static string GetDateFile()
{
return DateTime.Now.ToString("HHmmssff");
}
#endregion
#region Copy folders
/// <summary>
/// Copy folders ( recursive )
/// </summary>
/// <param name="varFromDirectory"> Source folder path </param>
/// <param name="varToDirectory"> Destination 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);
}
}
}
#endregion
#region Check the file , If the file does not exist, create it
/// <summary>
/// Check the file , If the file does not exist, create it
/// </summary>
/// <param name="FilePath"> The path , Include file name </param>
public static void ExistsFile(string FilePath)
{
//if(!File.Exists(FilePath))
//File.Create(FilePath);
// This will give you an error , See below for a detailed explanation .........
if (!File.Exists(FilePath))
{
FileStream fs = File.Create(FilePath);
fs.Close();
}
}
#endregion
#region Deletes files in the specified folder for other folders
/// <summary>
/// Deletes files in the specified folder for other folders
/// </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)
{
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("\\")));
}
}
}
#endregion
#region Gets the file name from the absolute path of the file ( Include extension )
/// <summary>
/// Gets the file name from the absolute path of the file ( Include extension )
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static string GetFileName(string filePath)
{
// Gets the name of the file
FileInfo fi = new FileInfo(filePath);
return fi.Name;
}
#endregion
/// <summary>
/// Copy file reference method , Reference in page
/// </summary>
/// <param name="cDir"> A new path </param>
/// <param name="TempId"> Template engine replacement number </param>
public static void CopyFiles(string cDir, string TempId)
{
//if (Directory.Exists(Request.PhysicalApplicationPath + "\\Controls"))
//{
// string TempStr = string.Empty;
// StreamWriter sw;
// if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Default.aspx"))
// {
// TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Default.aspx");
// TempStr = TempStr.Replace("{$ChannelId$}", TempId);
// sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Default.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
// sw.Write(TempStr);
// sw.Close();
// }
// if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Column.aspx"))
// {
// TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Column.aspx");
// TempStr = TempStr.Replace("{$ChannelId$}", TempId);
// sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\List.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
// sw.Write(TempStr);
// sw.Close();
// }
// if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Content.aspx"))
// {
// TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Content.aspx");
// TempStr = TempStr.Replace("{$ChannelId$}", TempId);
// sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\View.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
// sw.Write(TempStr);
// sw.Close();
// }
// if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\MoreDiss.aspx"))
// {
// TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\MoreDiss.aspx");
// TempStr = TempStr.Replace("{$ChannelId$}", TempId);
// sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\DissList.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
// sw.Write(TempStr);
// sw.Close();
// }
// if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\ShowDiss.aspx"))
// {
// TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\ShowDiss.aspx");
// TempStr = TempStr.Replace("{$ChannelId$}", TempId);
// sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Diss.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
// sw.Write(TempStr);
// sw.Close();
// }
// if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Review.aspx"))
// {
// TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Review.aspx");
// TempStr = TempStr.Replace("{$ChannelId$}", TempId);
// sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Review.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
// sw.Write(TempStr);
// sw.Close();
// }
// if (File.Exists(Request.PhysicalApplicationPath + "\\Controls\\Search.aspx"))
// {
// TempStr = File.ReadAllText(Request.PhysicalApplicationPath + "\\Controls\\Search.aspx");
// TempStr = TempStr.Replace("{$ChannelId$}", TempId);
// sw = new StreamWriter(Request.PhysicalApplicationPath + "\\" + cDir + "\\Search.aspx", false, System.Text.Encoding.GetEncoding("GB2312"));
// sw.Write(TempStr);
// sw.Close();
// }
//}
}
#region create 1 A directory
/// <summary>
/// create 1 A directory
/// </summary>
/// <param name="directoryPath"> The absolute path to the directory </param>
public static void CreateDirectory(string directoryPath)
{
// Create a directory if it does not exist
if (!IsExistDirectory(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
#endregion
#region create 1 A file
/// <summary>
/// create 1 A file.
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static void CreateFile(string filePath)
{
try
{
// If the file does not exist, create it
if (!IsExistFile(filePath))
{
// create 1 a FileInfo object
FileInfo file = new FileInfo(filePath);
// Create a file
FileStream fs = file.Create();
// Close file flow
fs.Close();
}
}
catch (Exception ex)
{
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
throw ex;
}
}
/// <summary>
/// create 1 A file , And writes the byte stream to the file.
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
/// <param name="buffer">2 Base stream data </param>
public static void CreateFile(string filePath, byte[] buffer)
{
try
{
// If the file does not exist, create it
if (!IsExistFile(filePath))
{
// create 1 a FileInfo object
FileInfo file = new FileInfo(filePath);
// Create a file
FileStream fs = file.Create();
// write 2 Base flow
fs.Write(buffer, 0, buffer.Length);
// Close file flow
fs.Close();
}
}
catch (Exception ex)
{
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
throw ex;
}
}
#endregion
#region Gets the number of lines in a text file
/// <summary>
/// Gets the number of lines in a text file
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static int GetLineCount(string filePath)
{
// Read each line of the text file 1 An array of strings
string[] rows = File.ReadAllLines(filePath);
// Returns the number of rows
return rows.Length;
}
#endregion
#region To obtain 1 The length of three files
/// <summary>
/// To obtain 1 The length of three files , The unit is Byte
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static int GetFileSize(string filePath)
{
// create 1 File object
FileInfo fi = new FileInfo(filePath);
// Gets the size of the file
return (int)fi.Length;
}
#endregion
#region Gets a list of subdirectories in the specified directory
/// <summary>
/// Gets a list of all subdirectories in the specified directory and subdirectories
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of the directory </param>
/// <param name="searchPattern"> Pattern string, "*" On behalf of 0 or N A character, "?" On behalf of 1 A character.
/// Example: "Log*.xml" Represents all searches to Log At the beginning of Xml File. </param>
/// <param name="isSearchChild"> Whether to search subdirectories </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;
}
}
#endregion
#region Writes to a text file
/// <summary>
/// Writes to a text file
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
/// <param name="text"> What is written </param>
/// <param name="encoding"> coding </param>
public static void WriteText(string filePath, string text, Encoding encoding)
{
// Writes to a file
File.WriteAllText(filePath, text, encoding);
}
#endregion
#region Appends content to the end of a text file
/// <summary>
/// Appends content to the end of a text file
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
/// <param name="content"> What is written </param>
public static void AppendText(string filePath, string content)
{
File.AppendAllText(filePath, content);
}
#endregion
#region Copies the contents of an existing file into a new file
/// <summary>
/// Copies the contents of the source file to the destination file
/// </summary>
/// <param name="sourceFilePath"> The absolute path of the source file </param>
/// <param name="destFilePath"> The absolute path to the destination file </param>
public static void Copy(string sourceFilePath, string destFilePath)
{
File.Copy(sourceFilePath, destFilePath, true);
}
#endregion
#region Moves the file to the specified directory
/// <summary>
/// Moves the file to the specified directory
/// </summary>
/// <param name="sourceFilePath"> The absolute path of the source file that needs to be moved </param>
/// <param name="descDirectoryPath"> The absolute path to the directory moved to </param>
public static void Move(string sourceFilePath, string descDirectoryPath)
{
// Gets the name of the source file
string sourceFileName = GetFileName(sourceFilePath);
if (IsExistDirectory(descDirectoryPath))
{
// If there is a file of the same name in the destination , Delete the
if (IsExistFile(descDirectoryPath + "\\" + sourceFileName))
{
DeleteFile(descDirectoryPath + "\\" + sourceFileName);
}
// Moves the file to the specified directory
File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
}
}
#endregion
#region Gets the file name from the absolute path of the file ( No extension is included )
/// <summary>
/// Gets the file name from the absolute path of the file ( No extension is included )
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static string GetFileNameNoExtension(string filePath)
{
// Gets the name of the file
FileInfo fi = new FileInfo(filePath);
return fi.Name.Split('.')[0];
}
#endregion
#region Gets the extension from the absolute path of the file
/// <summary>
/// Gets the extension from the absolute path of the file
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static string GetExtension(string filePath)
{
// Gets the name of the file
FileInfo fi = new FileInfo(filePath);
return fi.Extension;
}
#endregion
#region Empty the specified directory
/// <summary>
/// Empties all files and subdirectories in the specified directory , But the directory is still saved .
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of 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 < fileNames.Length; i++)
{
DeleteFile(fileNames[i]);
}
// Delete all subdirectories in the directory
string[] directoryNames = GetDirectories(directoryPath);
for (int i = 0; i < directoryNames.Length; i++)
{
DeleteDirectory(directoryNames[i]);
}
}
}
#endregion
#region Empty file contents
/// <summary>
/// Empty file contents
/// </summary>
/// <param name="filePath"> The absolute path to the file </param>
public static void ClearFile(string filePath)
{
// Delete the file
File.Delete(filePath);
// Recreate the file
CreateFile(filePath);
}
#endregion
#region Delete the specified directory
/// <summary>
/// Deletes the specified directory and all its subdirectories
/// </summary>
/// <param name="directoryPath"> Specifies the absolute path of the directory </param>
public static void DeleteDirectory(string directoryPath)
{
if (IsExistDirectory(directoryPath))
{
Directory.Delete(directoryPath, true);
}
}
#endregion
}
}
Hopefully this article has helped you with your C# programming.