1. 程式人生 > >C# 檔案及目錄操作類

C# 檔案及目錄操作類

轉自http://blog.csdn.net/joyhen/article/details/8572094

    public static class FileHelper  
    {  
        #region 檢測指定目錄是否存在  
        /// <summary>  
        /// 檢測指定目錄是否存在  
        /// </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);  
                return directoryNames.Length <= 0;  
            }  
            catch  
            {  
                return false;  
            }  
        }  
        #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);  
  
                //判斷指定檔案是否存在  
                return fileNames.Length != 0;  
            }  
            catch  
            {  
                return false;  
            }  
        }  
  
        /// <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);  
  
                //判斷指定檔案是否存在  
                return fileNames.Length != 0;  
            }  
            catch  
            {  
                return false;  
            }  
        }  
        #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 bool CreateFile(string filePath)  
        {  
            try  
            {  
                //如果檔案不存在則建立該檔案  
                if (!IsExistFile(filePath))  
                {  
                    //建立一個FileInfo物件  
                    FileInfo file = new FileInfo(filePath);  
                    //建立檔案  
                    FileStream fs = file.Create();  
                    //關閉檔案流  
                    fs.Close();  
                }  
            }  
            catch  
            {  
                return false;  
            }  
  
            return true;  
        }  
  
        /// <summary>  
        /// 建立一個檔案,並將位元組流寫入檔案。  
        /// </summary>  
        /// <param name="filePath">檔案的絕對路徑</param>  
        /// <param name="buffer">二進位制流資料</param>  
        public static bool 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  
            {  
                return false;  
            }  
            return true;  
        }  
        #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;  
        }  
  
        /// <summary>  
        /// 獲取一個檔案的長度,單位為KB  
        /// </summary>  
        /// <param name="filePath">檔案的路徑</param>          
        public static double GetFileSizeByKB(string filePath)  
        {  
            //建立一個檔案物件  
            FileInfo fi = new FileInfo(filePath);  
            long size = fi.Length / 1024;  
            //獲取檔案的大小  
            return double.Parse(size.ToString());  
        }  
  
        /// <summary>  
        /// 獲取一個檔案的長度,單位為MB  
        /// </summary>  
        /// <param name="filePath">檔案的路徑</param>          
        public static double GetFileSizeByMB(string filePath)  
        {  
            //建立一個檔案物件  
            FileInfo fi = new FileInfo(filePath);  
            long size = fi.Length / 1024 / 1024;  
            //獲取檔案的大小  
            return double.Parse(size.ToString());  
        }  
        #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  
            {  
                return Directory.GetFiles(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);  
            }  
            catch  
            {  
                return null;  
            }  
        }  
        #endregion  
 
        #region 獲取指定目錄中的子目錄列表  
        /// <summary>  
        /// 獲取指定目錄中所有子目錄列表,若要搜尋巢狀的子目錄列表,請使用過載方法.  
        /// </summary>  
        /// <param name="directoryPath">指定目錄的絕對路徑</param>          
        public static string[] GetDirectories(string directoryPath)  
        {  
            try  
            {  
                return Directory.GetDirectories(directoryPath);  
            }  
            catch  
            {  
                return null;  
            }  
        }  
  
        /// <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  
            {  
                return Directory.GetDirectories(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);  
            }  
            catch  
            {  
                throw null;  
            }  
        }  
        #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="stream">原始流</param>  
        public static byte[] StreamToBytes(Stream stream)  
        {  
            try  
            {  
                //建立緩衝區  
                byte[] buffer = new byte[stream.Length];  
  
                //讀取流  
                stream.Read(buffer, 0, int.Parse(stream.Length.ToString()));  
  
                //返回流  
                return buffer;  
            }  
            catch  
            {  
                return null;  
            }  
            finally  
            {  
                //關閉流  
                stream.Close();  
            }  
        }  
        #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  
            {  
                return null;  
            }  
            finally  
            {  
                //關閉檔案流  
                fs.Close();  
            }  
        }  
        #endregion  
 
        #region 將檔案讀取到字串中  
        /// <summary>  
        /// 將檔案讀取到字串中  
        /// </summary>  
        /// <param name="filePath">檔案的絕對路徑</param>  
        public static string FileToString(string filePath)  
        {  
            return FileToString(filePath, Encoding.Default);  
        }  
        /// <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  
            {  
                return string.Empty;  
            }  
            finally  
            {  
                //關閉流讀取器  
                reader.Close();  
            }  
        }  
        #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="directoryPath">指定目錄的絕對路徑</param>  
        public static void ClearDirectory(string directoryPath)  
        {  
            if (IsExistDirectory(directoryPath))  
            {  
                //刪除目錄中所有的檔案  
                string[] fileNames = GetFileNames(directoryPath);  
                foreach (string t in fileNames)  
                {  
                    DeleteFile(t);  
                }  
  
                //刪除目錄中所有的子目錄  
                string[] directoryNames = GetDirectories(directoryPath);  
                foreach (string t in directoryNames)  
                {  
                    DeleteDirectory(t);  
                }  
            }  
        }  
        #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 記錄錯誤日誌到檔案方法  
        /// <summary>  
        /// 記錄錯誤日誌到檔案方法  
        /// </summary>  
        /// <param name="exMessage"></param>  
        /// <param name="exMethod"></param>  
        /// <param name="userID"></param>  
        public static void ErrorLog(string exMessage, string exMethod, int userID)  
        {  
            try  
            {  
                string errVir = "/Log/Error/" + DateTime.Now.ToShortDateString() + ".txt";  
                string errPath = System.Web.HttpContext.Current.Server.MapPath(errVir);  
                File.AppendAllText(errPath,  
                                   "{userID:" + userID + ",exMedthod:" + exMethod + ",exMessage:" + exMessage + "}");  
            }  
            catch  
            {  
  
            }  
        }  
        #endregion  
 
        #region 輸出除錯日誌  
        /// <summary>  
        /// 輸出除錯日誌  
        /// </summary>  
        /// <param name="factValue">實際值</param>   
        /// <param name="expectValue">預期值</param>  
        public static void OutDebugLog(object factValue, object expectValue = null)  
        {  
            string errPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("/Log/Debug/{0}.html", DateTime.Now.ToShortDateString()));  
            if (!Equals(expectValue, null))  
                File.AppendAllLines(errPath,  
                                   new[]{string.Format(  
                                       "【{0}】[{3}] 實際值:<span style='color:blue;'>{1}</span> 預期值: <span style='color:gray;'>{2}</span><br/>",  
                                       DateTime.Now.ToShortTimeString()  
                                       , factValue, expectValue, Equals(expectValue, factValue)  
                                           ? "<span style='color:green;'>成功</span>"  
                                           : "<span style='color:red;'>失敗</span>")});  
            else  
                File.AppendAllLines(errPath, new[]{  
                               string.Format(  
                                   "【{0}】[{3}] 實際值:<span style='color:blue;'>{1}</span> 預期值: <span style='color:gray;'>{2}</span><br/>",  
                                   DateTime.Now.ToShortTimeString()  
                                   , factValue, "空", "<span style='color:green;'>成功</span>")});  
        }  
        #endregion  
    }  
}