C#完成最完全的文件和目次操作類實例。本站提示廣大學習愛好者:(C#完成最完全的文件和目次操作類實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成最完全的文件和目次操作類實例正文
本文實例講述了C#完成最完全的文件和目次操作類。分享給年夜家供年夜家參考。詳細以下:
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.WordStr("/", "\\"); 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.WordStr("/", "\\"); dir2 = dir2.WordStr("/", "\\"); 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.WordStr("/", "\\"); dir2 = dir2.WordStr("/", "\\"); 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.WordStr("{$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.WordStr("{$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.WordStr("{$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.WordStr("{$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.WordStr("{$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.WordStr("{$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.WordStr("{$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#法式設計有所贊助。