C#中檔案操作整理
阿新 • • 發佈:2019-02-10
直接上程式碼:(其中有些引用在C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0)你的VS安裝目錄,具體請自行百度。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.IO.Packaging; using System.Xml; using System.Web; namespace YcPackageTool.Utils { class FileIOManager { #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 writeText2File(string filePath, string content) { //向檔案寫入內容 File.WriteAllText(filePath, content); } #endregion #region 向文字檔案的尾部追加內容 /// <summary> /// 向文字檔案的尾部追加內容 /// </summary> /// <param name="filePath">檔案的絕對路徑</param> /// <param name="content">寫入的內容</param> public static void appendText2File(string filePath, string content) { File.AppendAllText(filePath, content); } #endregion #region 將現有檔案的內容複製到新檔案中 /// <summary> /// 將原始檔的內容複製到目標檔案中 /// </summary> /// <param name="sourceFilePath">原始檔的絕對路徑</param> /// <param name="destFilePath">目標檔案的絕對路徑</param> public static bool copyFile(string sourceFilePath, string destFilePath, bool ignoreRepeat = true) { if (!ignoreRepeat && isExistFile(destFilePath)) { LogUtil.PtShowLog("檔案有重複 正在合併中....."); mergeFileByRepeatName(sourceFilePath, destFilePath); return true; } File.Copy(sourceFilePath, destFilePath, ignoreRepeat); return true; } #endregion #region 拷貝資料夾 /// <summary> /// 拷貝資料夾 /// </summary> /// <param name="sourcePath">原始檔夾絕對路徑</param> /// <param name="destPath">目的資料夾絕對路徑</param> /// <param name="ignoreRepeat">是否忽略檔案重複</param> /// <returns>拷貝結果</returns> public static bool copyDirectory(string sourcePath, string destPath, bool ignoreRepeat = true) { if (!isExistDirectory(sourcePath)) { return false; } createDirectory(destPath); string[] _dicNames = getDirectories(sourcePath, "*", true); if (null != _dicNames) { foreach (string _dicName in _dicNames) { string _newDiectory = _dicName.Replace(sourcePath, destPath); createDirectory(_newDiectory); } } string[] _fileNames = getFileNames(sourcePath, "*", true); if (null != _fileNames) { foreach (string _fileName in _fileNames) { string _newFile = _fileName.Replace(sourcePath, destPath); copyFile(_fileName, _newFile, ignoreRepeat); } } return true; } #endregion #region 合併重複檔名的檔案 /// <summary> /// 合併重複檔名的檔案 /// </summary> /// <param name="source"></param> /// <param name="des"></param> private static void mergeFileByRepeatName(String source, String des) { if (source.Substring(source.Length - 3, 3) == "xml") { XmlDocument doc1 = new XmlDocument(); doc1.Load(source); XmlDocument doc2 = new XmlDocument(); doc2.Load(des); XmlNode root1 = doc1.DocumentElement; foreach (XmlNode n in doc2.DocumentElement.ChildNodes) { XmlNode root2 = doc1.ImportNode(n, true); root1.AppendChild(root2); } doc1.Save(des); } } #endregion #region 將檔案移動到指定目錄 /// <summary> /// 將檔案移動到指定目錄 /// </summary> /// <param name="sourceFilePath">需要移動的原始檔的絕對路徑</param> /// <param name="descDirectoryPath">移動到的目錄的絕對路徑</param> public static void moveFile2Directory(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> /// 讀取檔案到StringBuilder 預設編碼 /// </summary> /// <param name="filePath">檔案路徑</param> /// <returns></returns> public static StringBuilder readFile(String filePath) { return readFile(filePath, Encoding.Default); } #endregion #region 讀取檔案(指定編碼) /// <summary> /// 讀取檔案到StringBuilder 指定編碼 /// </summary> /// <param name="filePath">檔案路徑</param> /// <param name="encoding">檔案編碼方式</param> /// <returns></returns> public static StringBuilder readFile(String filePath, Encoding encoding) { if (File.Exists(filePath)) { StreamReader _sr = new StreamReader(filePath, encoding); String _line; StringBuilder _str = new StringBuilder(); while ((_line = _sr.ReadLine()) != null) { _str.Append(_line + "\r\n"); } _sr.Close(); return _str; } else { return null; } } #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> /// <param name="extension"></param> /// <returns></returns> public static bool CheckExtension(string filePath, string extension) { string _extension = getExtension(filePath); if (null == extension || extension.Length == 0) { return false; } if (null == _extension || _extension.Length == 0) { return false; } if (extension.Equals(_extension)) { return true; } return false; } #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 clearFileContent(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> /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification /// </summary> /// <param name="folderName">The folder to extract the package to</param> /// <param name="compressedFileName">The package file</param> /// <param name="overrideExisting">override existing files</param> /// <returns></returns> public static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting) { bool result = false; try { if (!File.Exists(compressedFileName)) { return result; } DirectoryInfo directoryInfo = new DirectoryInfo(folderName); if (!directoryInfo.Exists) directoryInfo.Create(); using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read)) { foreach (PackagePart packagePart in package.GetParts()) { extractPart(packagePart, folderName, overrideExisting); } } result = true; } catch (Exception e) { throw new Exception("Error unzipping file " + compressedFileName, e); } return result; } public static void extractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting) { string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/'); if (!Directory.Exists(Path.GetDirectoryName(stringPart))) Directory.CreateDirectory(Path.GetDirectoryName(stringPart)); if (!overrideExisting && File.Exists(stringPart)) return; using (FileStream fileStream = new FileStream(stringPart, FileMode.Create)) { packagePart.GetStream().CopyTo(fileStream); } } #endregion #region 記錄錯誤日誌到檔案方法 /// <summary> /// 記錄錯誤日誌到檔案方法 /// </summary> /// <param name="exMessage"></param> /// <param name="exMethod"></param> /// <param name="userID"></param> /// <param name="logPath">在指定目錄下建立日誌檔案</param> /// <param name="currentDir">如果為true,則在當前目錄下建立Log資料夾的日誌檔案</param> public static void errorLog2File(string exMessage, string exMethod, int userID, string logPath, bool currentDir) { try { string errVir = "/Log/Error/" + DateTime.Now.ToShortDateString() + ".txt"; string errPath = currentDir ? (Environment.CurrentDirectory + "\\Log\\") : logPath; File.AppendAllText(errPath, "{userID:" + userID + ",exMedthod:" + exMethod + ",exMessage:" + exMessage + "}"); } catch { } } #endregion } }
【歡迎上碼】
【微信公眾號搜尋 h2o2s2】