史上最完整的文件和目录操作类
生活随笔
收集整理的這篇文章主要介紹了
史上最完整的文件和目录操作类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【文件操作類】史上最完整的文件和目錄操作類
<a target=_blank href="http://bbs.cskin.net/thread-114-1-1.html">http://bbs.cskin.net/thread-114-1-1.html</a>
(出處: CSkin論壇)
?一個非常非常完整強大的文件和文件夾操作類,基于System.IO下面的Directory和File擴展出了我們經常要用到的但是系統不自帶的方法例如:<ul class="litype_1" type="1"><li>獲取一個目錄下面的所有文件。</li><li>支持遍歷子目錄、驗證目錄是否為空。</li><li>移動復制文件、批量刪除文件以及對文件的寫入、修改、追加對目錄的清空等多個方法。</li></ul>
using System;
using System.Text;
using System.IO;namespace HelloCsharp.Utilities
{/// <summary>/// 文件操作類/// </summary>public static class DirFile{#region 檢測指定目錄是否存在/// <summary>/// 檢測指定目錄是否存在/// </summary>/// <param name="directoryPath">目錄的絕對路徑</param>/// <returns></returns>public static bool IsExistDirectory(string directoryPath){return Directory.Exists(directoryPath);}#endregion#region 檢測指定文件是否存在,如果存在返回true/// <summary>/// 檢測指定文件是否存在,如果存在則返回true。/// </summary>/// <param name="filePath">文件的絕對路徑</param> public static bool IsExistFile(string filePath){return File.Exists(filePath);}#endregion#region 獲取指定目錄中的文件列表/// <summary>/// 獲取指定目錄中所有文件列表/// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param> public static string[] GetFileNames(string directoryPath){//如果目錄不存在,則拋出異常if (!IsExistDirectory(directoryPath)){throw new FileNotFoundException();}//獲取文件列表return Directory.GetFiles(directoryPath);}#endregion#region 獲取指定目錄中所有子目錄列表,若要搜索嵌套的子目錄列表,請使用重載方法./// <summary>/// 獲取指定目錄中所有子目錄列表,若要搜索嵌套的子目錄列表,請使用重載方法./// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param> public static string[] GetDirectories(string directoryPath){try{return Directory.GetDirectories(directoryPath);}catch (IOException ex){throw ex;}}#endregion#region 獲取指定目錄及子目錄中所有文件列表/// <summary>/// 獲取指定目錄及子目錄中所有文件列表/// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param>/// <param name="searchPattern">模式字符串,"*"代表0或N個字符,"?"代表1個字符。/// 范例:"Log*.xml"表示搜索所有以Log開頭的Xml文件。</param>/// <param name="isSearchChild">是否搜索子目錄</param>public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild){//如果目錄不存在,則拋出異常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 檢測指定目錄是否為空/// <summary>/// 檢測指定目錄是否為空/// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param> public static bool IsEmptyDirectory(string directoryPath){try{//判斷是否存在文件string[] fileNames = GetFileNames(directoryPath);if (fileNames.Length > 0){return false;}//判斷是否存在文件夾string[] directoryNames = GetDirectories(directoryPath);if (directoryNames.Length > 0){return false;}return true;}catch{//這里記錄日志//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);return true;}}#endregion#region 檢測指定目錄中是否存在指定的文件/// <summary>/// 檢測指定目錄中是否存在指定的文件,若要搜索子目錄請使用重載方法./// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param>/// <param name="searchPattern">模式字符串,"*"代表0或N個字符,"?"代表1個字符。/// 范例:"Log*.xml"表示搜索所有以Log開頭的Xml文件。</param> public static bool Contains(string directoryPath, string searchPattern){try{//獲取指定的文件列表string[] fileNames = GetFileNames(directoryPath, searchPattern, false);//判斷指定文件是否存在if (fileNames.Length == 0){return false;}else{return true;}}catch (Exception ex){throw new Exception(ex.Message);//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);}}/// <summary>/// 檢測指定目錄中是否存在指定的文件/// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param>/// <param name="searchPattern">模式字符串,"*"代表0或N個字符,"?"代表1個字符。/// 范例:"Log*.xml"表示搜索所有以Log開頭的Xml文件。</param> /// <param name="isSearchChild">是否搜索子目錄</param>public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild){try{//獲取指定的文件列表string[] fileNames = GetFileNames(directoryPath, searchPattern, true);//判斷指定文件是否存在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 創建目錄/// <summary>/// 創建目錄/// </summary>/// <param name="dir">要創建的目錄路徑包括目錄名</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 刪除目錄/// <summary>/// 刪除目錄/// </summary>/// <param name="dir">要刪除的目錄路徑和名稱</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 刪除文件/// <summary>/// 刪除文件/// </summary>/// <param name="file">要刪除的文件路徑和名稱</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 創建文件/// <summary>/// 創建文件/// </summary>/// <param name="dir">帶后綴的文件名</param>/// <param name="pagestr">文件內容</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 移動文件(剪貼--粘貼)/// <summary>/// 移動文件(剪貼--粘貼)/// </summary>/// <param name="dir1">要移動的文件的路徑及全名(包括后綴)</param>/// <param name="dir2">文件移動到新的位置,并指定新的文件名</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 復制文件/// <summary>/// 復制文件/// </summary>/// <param name="dir1">要復制的文件的路徑已經全名(包括后綴)</param>/// <param name="dir2">目標位置,并指定新的文件名</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 根據時間得到目錄名 / 格式:yyyyMMdd 或者 HHmmssff/// <summary>/// 根據時間得到目錄名yyyyMMdd/// </summary>/// <returns></returns>public static string GetDateDir(){return DateTime.Now.ToString("yyyyMMdd");}/// <summary>/// 根據時間得到文件名HHmmssff/// </summary>/// <returns></returns>public static string GetDateFile(){return DateTime.Now.ToString("HHmmssff");}#endregion#region 復制文件夾/// <summary>/// 復制文件夾(遞歸)/// </summary>/// <param name="varFromDirectory">源文件夾路徑</param>/// <param name="varToDirectory">目標文件夾路徑</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 檢查文件,如果文件不存在則創建/// <summary>/// 檢查文件,如果文件不存在則創建 /// </summary>/// <param name="FilePath">路徑,包括文件名</param>public static void ExistsFile(string FilePath){//if(!File.Exists(FilePath)) //File.Create(FilePath); //以上寫法會報錯,詳細解釋請看下文......... if (!File.Exists(FilePath)){FileStream fs = File.Create(FilePath);fs.Close();}}#endregion#region 刪除指定文件夾對應其他文件夾里的文件/// <summary>/// 刪除指定文件夾對應其他文件夾里的文件/// </summary>/// <param name="varFromDirectory">指定文件夾路徑</param>/// <param name="varToDirectory">對應其他文件夾路徑</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 從文件的絕對路徑中獲取文件名( 包含擴展名 )/// <summary>/// 從文件的絕對路徑中獲取文件名( 包含擴展名 )/// </summary>/// <param name="filePath">文件的絕對路徑</param> public static string GetFileName(string filePath){//獲取文件的名稱FileInfo fi = new FileInfo(filePath);return fi.Name;}#endregion/// <summary>/// 復制文件參考方法,頁面中引用/// </summary>/// <param name="cDir">新路徑</param>/// <param name="TempId">模板引擎替換編號</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 創建一個目錄/// <summary>/// 創建一個目錄/// </summary>/// <param name="directoryPath">目錄的絕對路徑</param>public static void CreateDirectory(string directoryPath){//如果目錄不存在則創建該目錄if (!IsExistDirectory(directoryPath)){Directory.CreateDirectory(directoryPath);}}#endregion#region 創建一個文件/// <summary>/// 創建一個文件。/// </summary>/// <param name="filePath">文件的絕對路徑</param>public static void CreateFile(string filePath){try{//如果文件不存在則創建該文件if (!IsExistFile(filePath)){//創建一個FileInfo對象FileInfo file = new FileInfo(filePath);//創建文件FileStream fs = file.Create();//關閉文件流fs.Close();}}catch (Exception ex){//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);throw ex;}}/// <summary>/// 創建一個文件,并將字節流寫入文件。/// </summary>/// <param name="filePath">文件的絕對路徑</param>/// <param name="buffer">二進制流數據</param>public static void CreateFile(string filePath, byte[] buffer){try{//如果文件不存在則創建該文件if (!IsExistFile(filePath)){//創建一個FileInfo對象FileInfo file = new FileInfo(filePath);//創建文件FileStream fs = file.Create();//寫入二進制流fs.Write(buffer, 0, buffer.Length);//關閉文件流fs.Close();}}catch (Exception ex){//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);throw ex;}}#endregion#region 獲取文本文件的行數/// <summary>/// 獲取文本文件的行數/// </summary>/// <param name="filePath">文件的絕對路徑</param> public static int GetLineCount(string filePath){//將文本文件的各行讀到一個字符串數組中string[] rows = File.ReadAllLines(filePath);//返回行數return rows.Length;}#endregion#region 獲取一個文件的長度/// <summary>/// 獲取一個文件的長度,單位為Byte/// </summary>/// <param name="filePath">文件的絕對路徑</param> public static int GetFileSize(string filePath){//創建一個文件對象FileInfo fi = new FileInfo(filePath);//獲取文件的大小return (int)fi.Length;}#endregion#region 獲取指定目錄中的子目錄列表/// <summary>/// 獲取指定目錄及子目錄中所有子目錄列表/// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param>/// <param name="searchPattern">模式字符串,"*"代表0或N個字符,"?"代表1個字符。/// 范例:"Log*.xml"表示搜索所有以Log開頭的Xml文件。</param>/// <param name="isSearchChild">是否搜索子目錄</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 向文本文件寫入內容/// <summary>/// 向文本文件中寫入內容/// </summary>/// <param name="filePath">文件的絕對路徑</param>/// <param name="text">寫入的內容</param>/// <param name="encoding">編碼</param>public static void WriteText(string filePath, string text, Encoding encoding){//向文件寫入內容File.WriteAllText(filePath, text, encoding);}#endregion#region 向文本文件的尾部追加內容/// <summary>/// 向文本文件的尾部追加內容/// </summary>/// <param name="filePath">文件的絕對路徑</param>/// <param name="content">寫入的內容</param>public static void AppendText(string filePath, string content){File.AppendAllText(filePath, content);}#endregion#region 將現有文件的內容復制到新文件中/// <summary>/// 將源文件的內容復制到目標文件中/// </summary>/// <param name="sourceFilePath">源文件的絕對路徑</param>/// <param name="destFilePath">目標文件的絕對路徑</param>public static void Copy(string sourceFilePath, string destFilePath){File.Copy(sourceFilePath, destFilePath, true);}#endregion#region 將文件移動到指定目錄/// <summary>/// 將文件移動到指定目錄/// </summary>/// <param name="sourceFilePath">需要移動的源文件的絕對路徑</param>/// <param name="descDirectoryPath">移動到的目錄的絕對路徑</param>public static void Move(string sourceFilePath, string descDirectoryPath){//獲取源文件的名稱string sourceFileName = GetFileName(sourceFilePath);if (IsExistDirectory(descDirectoryPath)){//如果目標中存在同名文件,則刪除if (IsExistFile(descDirectoryPath + "\\" + sourceFileName)){DeleteFile(descDirectoryPath + "\\" + sourceFileName);}//將文件移動到指定目錄File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);}}#endregion#region 從文件的絕對路徑中獲取文件名( 不包含擴展名 )/// <summary>/// 從文件的絕對路徑中獲取文件名( 不包含擴展名 )/// </summary>/// <param name="filePath">文件的絕對路徑</param> public static string GetFileNameNoExtension(string filePath){//獲取文件的名稱FileInfo fi = new FileInfo(filePath);return fi.Name.Split('.')[0];}#endregion#region 從文件的絕對路徑中獲取擴展名/// <summary>/// 從文件的絕對路徑中獲取擴展名/// </summary>/// <param name="filePath">文件的絕對路徑</param> public static string GetExtension(string filePath){//獲取文件的名稱FileInfo fi = new FileInfo(filePath);return fi.Extension;}#endregion#region 清空指定目錄/// <summary>/// 清空指定目錄下所有文件及子目錄,但該目錄依然保存./// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param>public static void ClearDirectory(string directoryPath){if (IsExistDirectory(directoryPath)){//刪除目錄中所有的文件string[] fileNames = GetFileNames(directoryPath);for (int i = 0; i < fileNames.Length; i++){DeleteFile(fileNames);}//刪除目錄中所有的子目錄string[] directoryNames = GetDirectories(directoryPath);for (int i = 0; i < directoryNames.Length; i++){DeleteDirectory(directoryNames);}}}#endregion#region 清空文件內容/// <summary>/// 清空文件內容/// </summary>/// <param name="filePath">文件的絕對路徑</param>public static void ClearFile(string filePath){//刪除文件File.Delete(filePath);//重新創建該文件CreateFile(filePath);}#endregion#region 刪除指定目錄/// <summary>/// 刪除指定目錄及其所有子目錄/// </summary>/// <param name="directoryPath">指定目錄的絕對路徑</param>public static void DeleteDirectory(string directoryPath){if (IsExistDirectory(directoryPath)){Directory.Delete(directoryPath, true);}}#endregion}
}
總結
以上是生活随笔為你收集整理的史上最完整的文件和目录操作类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c# Application.DoEve
- 下一篇: 最全的C#图片处理类ImageHelpe