1. 程式人生 > 實用技巧 >檔案操作幫助類

檔案操作幫助類

/// <summary>
   /// 檔案操作幫助類
   /// </summary>
   public class FileHelper
    {
        #region 檢測指定目錄是否存在
        /// <summary> 
        /// 檢測指定目錄是否存在,如果存在則返回true。
        /// </summary> 
        /// <param name="directoryPath">目錄的絕對路徑</param>         
        public static bool IsExistDirectory(string
directoryPath) { return Directory.Exists(directoryPath); } #endregion #region 檢測指定檔案是否存在 /// <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 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 (Exception ex) { throw ex; } } #endregion #region 檢測指定目錄中是否存在指定的檔案 /// <summary> /// 檢測指定目錄中是否存在指定的檔案,若要搜尋子目錄請使用過載方法. /// </summary> /// <param name="directoryPath">指定目錄的絕對路徑</param> /// <param name="searchPattern">模式字串,"*"代表0或N個字元,"?"代表1個字元。 /// 範例:"Log*.xml"表示搜尋所有以Log開頭的Xml檔案。</param> public static bool IsContainsFile(string directoryPath, string searchPattern) { try { //獲取指定的檔案列表 string[] fileNames = GetFileNames(directoryPath, searchPattern, false); //判斷指定檔案是否存在 if (fileNames.Length == 0) { return false; } else { return true; } } catch (Exception ex) { throw ex; } } /// <summary> /// 檢測指定目錄中是否存在指定的檔案 /// </summary> /// <param name="directoryPath">指定目錄的絕對路徑</param> /// <param name="searchPattern">模式字串,"*"代表0或N個字元,"?"代表1個字元。 /// 範例:"Log*.xml"表示搜尋所有以Log開頭的Xml檔案。</param> /// <param name="isSearchChild">是否搜尋子目錄</param> public static bool IsContainsFile(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 ex; } } #endregion #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) { 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) { 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> public static string[] GetFileNames(string directoryPath) { //如果目錄不存在,則丟擲異常 if (!IsExistDirectory(directoryPath)) { throw new FileNotFoundException(); } //獲取檔案列表 return Directory.GetFiles(directoryPath); } /// <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 string[] GetDirectories(string directoryPath) { try { return Directory.GetDirectories(directoryPath); } catch (IOException ex) { throw ex; } } /// <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="content">寫入的內容</param> public static void WriteText(string filePath, string content) { //向檔案寫入內容 File.WriteAllText(filePath, content); } #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 GetFileName(string filePath) { //獲取檔案的名稱 FileInfo fi = new FileInfo(filePath); return fi.Name; } #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="filePath">檔案的絕對路徑</param> public static byte[] FileToBytes(string filePath) { //獲取檔案的大小 int fileSize = GetFileSize(filePath); //建立一個臨時緩衝區 byte[] buffer = new byte[fileSize]; //建立一個檔案流 FileInfo fi = new FileInfo(filePath); FileStream fs = fi.Open(FileMode.Open); try { //將檔案流讀入緩衝區 fs.Read(buffer, 0, fileSize); return buffer; } catch (IOException ex) { throw ex; } finally { //關閉檔案流 fs.Close(); } } #endregion #region 將檔案讀取到字串中 /// <summary> /// 將檔案讀取到字串中 /// </summary> /// <param name="filePath">檔案的絕對路徑</param> /// <param name="encoding">字元編碼</param> public static string FileToString(string filePath, Encoding encoding) { //建立流讀取器 StreamReader reader = new StreamReader(filePath, encoding); try { //讀取流 return reader.ReadToEnd(); } catch (Exception ex) { throw ex; } finally { //關閉流讀取器 reader.Close(); } } #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[i]); } //刪除目錄中所有的子目錄 string[] directoryNames = GetDirectories(directoryPath); for (int i = 0; i < directoryNames.Length; i++) { DeleteDirectory(directoryNames[i]); } } } #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="filePath">檔案的絕對路徑</param> public static void DeleteFile(string filePath) { if (IsExistFile(filePath)) { File.Delete(filePath); } } #endregion #region 刪除指定目錄 /// <summary> /// 刪除指定目錄及其所有子目錄 /// </summary> /// <param name="directoryPath">指定目錄的絕對路徑</param> public static void DeleteDirectory(string directoryPath) { if (IsExistDirectory(directoryPath)) { Directory.Delete(directoryPath, true); } } #endregion #region 將位元組(B)轉換成兆(M),並保留兩位小數 /// <summary> /// 將位元組(B)轉換成兆(M),並保留兩位小數 /// </summary> public static string ConvertByteToMB(int byteLength) { return Math.Round((double)byteLength / (1024 * 1024), 2).ToString() + "M"; } #endregion #region 去除檔名中的特殊字元 public static string ReplaceBadCharOfFileName(string fileName) { fileName = fileName.Replace("\\", string.Empty); fileName = fileName.Replace("/", string.Empty); fileName = fileName.Replace(":", string.Empty); fileName = fileName.Replace("*", string.Empty); fileName = fileName.Replace("?", string.Empty); fileName = fileName.Replace("\"", string.Empty); fileName = fileName.Replace("<", string.Empty); fileName = fileName.Replace(">", string.Empty); fileName = fileName.Replace("|", string.Empty); fileName = fileName.Replace(" ", string.Empty); return fileName.ToString(); } #endregion }