C#文件操作輔助類FileUtil
Stream、byte[] 和 文件之間的轉(zhuǎn)換
將流讀取到緩沖區(qū)中
將 byte[] 轉(zhuǎn)成 Stream
將 Stream 寫入文件
從文件讀取 Stream
將文件讀取到緩沖區(qū)中
將文件讀取到字符串中
從嵌入資源中讀取文件內(nèi)容(e.g: xml).
獲取文件的編碼類型
獲取文件編碼
獲取一個(gè)文件的長度,單位為Byte
向文本文件中寫入內(nèi)容
將源文件的內(nèi)容復(fù)制到目標(biāo)文件中
獲取文本文件的行數(shù)
XML文件操作
從XML文件轉(zhuǎn)換為Object對(duì)象類型.
保存對(duì)象到特定格式的XML文件
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Cryptography; using System.Reflection; namespace JsonsHelper { /// <summary> /// 常用的文件操作輔助類FileUtil /// </summary> public class FileUtil { #region Stream、byte[] 和 文件之間的轉(zhuǎn)換 /// <summary> /// 將流讀取到緩沖區(qū)中 /// </summary> /// <param name="stream">原始流</param> public static byte[] StreamToBytes(Stream stream) { try { //創(chuàng)建緩沖區(qū) byte[] buffer = new byte[stream.Length]; //讀取流 stream.Read(buffer, 0, Convert.ToInt32(stream.Length)); //返回流 return buffer; } catch (IOException ex) { throw ex; } finally { //關(guān)閉流 stream.Close(); } } /// <summary> /// 將 byte[] 轉(zhuǎn)成 Stream /// </summary> public static Stream BytesToStream(byte[] bytes) { Stream stream = new MemoryStream(bytes); return stream; } /// <summary> /// 將 Stream 寫入文件 /// </summary> public static void StreamToFile(Stream stream, string fileName) { // 把 Stream 轉(zhuǎn)換成 byte[] byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 設(shè)置當(dāng)前流的位置為流的開始 stream.Seek(0, SeekOrigin.Begin); // 把 byte[] 寫入文件 FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); } /// <summary> /// 從文件讀取 Stream /// </summary> public static Stream FileToStream(string fileName) { // 打開文件 FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); // 讀取文件的 byte[] byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); // 把 byte[] 轉(zhuǎn)換成 Stream Stream stream = new MemoryStream(bytes); return stream; } /// <summary> /// 將文件讀取到緩沖區(qū)中 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static byte[] FileToBytes(string filePath) { //獲取文件的大小 int fileSize = GetFileSize(filePath); //創(chuàng)建一個(gè)臨時(shí)緩沖區(qū) byte[] buffer = new byte[fileSize]; //創(chuàng)建一個(gè)文件流 FileInfo fi = new FileInfo(filePath); FileStream fs = fi.Open(FileMode.Open); try { //將文件流讀入緩沖區(qū) fs.Read(buffer, 0, fileSize); return buffer; } catch (IOException ex) { throw ex; } finally { //關(guān)閉文件流 fs.Close(); } } /// <summary> /// 將文件讀取到字符串中 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static string FileToString(string filePath) { return FileToString(filePath, Encoding.Default); } /// <summary> /// 將文件讀取到字符串中 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> /// <param name="encoding">字符編碼</param> public static string FileToString(string filePath, Encoding encoding) { try { //創(chuàng)建流讀取器 using (StreamReader reader = new StreamReader(filePath, encoding)) { //讀取流 return reader.ReadToEnd(); } } catch (IOException ex) { throw ex; } } /// <summary> /// 從嵌入資源中讀取文件內(nèi)容(e.g: xml). /// </summary> /// <param name="fileWholeName">嵌入資源文件名,包括項(xiàng)目的命名空間.</param> /// <returns>資源中的文件內(nèi)容.</returns> public static string ReadFileFromEmbedded(string fileWholeName) { string result = string.Empty; using (TextReader reader = new StreamReader( Assembly.GetExecutingAssembly().GetManifestResourceStream(fileWholeName))) { result = reader.ReadToEnd(); } return result; } #endregion #region 獲取文件的編碼類型 /// <summary> /// 獲取文件編碼 /// </summary> /// <param name="filePath">文件絕對(duì)路徑</param> /// <returns></returns> public static Encoding GetEncoding(string filePath) { return GetEncoding(filePath, Encoding.Default); } /// <summary> /// 獲取文件編碼 /// </summary> /// <param name="filePath">文件絕對(duì)路徑</param> /// <param name="defaultEncoding">找不到則返回這個(gè)默認(rèn)編碼</param> /// <returns></returns> public static Encoding GetEncoding(string filePath, Encoding defaultEncoding) { Encoding targetEncoding = defaultEncoding; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4)) { if (fs != null && fs.Length >= 2) { long pos = fs.Position; fs.Position = 0; int[] buffer = new int[4]; //long x = fs.Seek(0, SeekOrigin.Begin); //fs.Read(buffer,0,4); buffer[0] = fs.ReadByte(); buffer[1] = fs.ReadByte(); buffer[2] = fs.ReadByte(); buffer[3] = fs.ReadByte(); fs.Position = pos; if (buffer[0] == 0xFE && buffer[1] == 0xFF)//UnicodeBe { targetEncoding = Encoding.BigEndianUnicode; } if (buffer[0] == 0xFF && buffer[1] == 0xFE)//Unicode { targetEncoding = Encoding.Unicode; } if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)//UTF8 { targetEncoding = Encoding.UTF8; } } } return targetEncoding; } #endregion #region 文件操作 #region 獲取一個(gè)文件的長度 /// <summary> /// 獲取一個(gè)文件的長度,單位為Byte /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static int GetFileSize(string filePath) { //創(chuàng)建一個(gè)文件對(duì)象 FileInfo fi = new FileInfo(filePath); //獲取文件的大小 return (int)fi.Length; } /// <summary> /// 獲取一個(gè)文件的長度,單位為KB /// </summary> /// <param name="filePath">文件的路徑</param> public static double GetFileSizeKB(string filePath) { //創(chuàng)建一個(gè)文件對(duì)象 FileInfo fi = new FileInfo(filePath); //獲取文件的大小 return ConvertHelper.ToDouble(Convert.ToDouble(fi.Length) / 1024, 1); } /// <summary> /// 獲取一個(gè)文件的長度,單位為MB /// </summary> /// <param name="filePath">文件的路徑</param> public static double GetFileSizeMB(string filePath) { //創(chuàng)建一個(gè)文件對(duì)象 FileInfo fi = new FileInfo(filePath); //獲取文件的大小 return ConvertHelper.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024, 1); } #endregion /// <summary> /// 向文本文件中寫入內(nèi)容 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> /// <param name="content">寫入的內(nèi)容</param> public static void WriteText(string filePath, string content) { //向文件寫入內(nèi)容 File.WriteAllText(filePath, content, Encoding.Default); } /// <summary> /// 向文本文件的尾部追加內(nèi)容 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> /// <param name="content">寫入的內(nèi)容</param> public static void AppendText(string filePath, string content) { File.AppendAllText(filePath, content, Encoding.Default); } /// <summary> /// 將源文件的內(nèi)容復(fù)制到目標(biāo)文件中 /// </summary> /// <param name="sourceFilePath">源文件的絕對(duì)路徑</param> /// <param name="destFilePath">目標(biāo)文件的絕對(duì)路徑</param> public static void Copy(string sourceFilePath, string destFilePath) { File.Copy(sourceFilePath, destFilePath, true); } /// <summary> /// 將文件移動(dòng)到指定目錄 /// </summary> /// <param name="sourceFilePath">需要移動(dòng)的源文件的絕對(duì)路徑</param> /// <param name="descDirectoryPath">移動(dòng)到的目錄的絕對(duì)路徑</param> public static void Move(string sourceFilePath, string descDirectoryPath) { //獲取源文件的名稱 string sourceFileName = GetFileName(sourceFilePath); if (Directory.Exists(descDirectoryPath)) { //如果目標(biāo)中存在同名文件,則刪除 if (IsExistFile(descDirectoryPath "\\" sourceFileName)) { DeleteFile(descDirectoryPath "\\" sourceFileName); } //將文件移動(dòng)到指定目錄 File.Move(sourceFilePath, descDirectoryPath "\\" sourceFileName); } } /// <summary> /// 檢測指定文件是否存在,如果存在則返回true。 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static bool IsExistFile(string filePath) { return File.Exists(filePath); } /// <summary> /// 創(chuàng)建一個(gè)文件。 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static void CreateFile(string filePath) { try { //如果文件不存在則創(chuàng)建該文件 if (!IsExistFile(filePath)) { File.Create(filePath); } } catch (IOException ex) { throw ex; } } /// <summary> /// 創(chuàng)建一個(gè)文件,并將字節(jié)流寫入文件。 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> /// <param name="buffer">二進(jìn)制流數(shù)據(jù)</param> public static void CreateFile(string filePath, byte[] buffer) { try { //如果文件不存在則創(chuàng)建該文件 if (!IsExistFile(filePath)) { //創(chuàng)建文件 using (FileStream fs = File.Create(filePath)) { //寫入二進(jìn)制流 fs.Write(buffer, 0, buffer.Length); } } } catch (IOException ex) { throw ex; } } /// <summary> /// 獲取文本文件的行數(shù) /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static int GetLineCount(string filePath) { //將文本文件的各行讀到一個(gè)字符串?dāng)?shù)組中 string[] rows = File.ReadAllLines(filePath); //返回行數(shù) return rows.Length; } /// <summary> /// 從文件的絕對(duì)路徑中獲取文件名( 包含擴(kuò)展名 ) /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static string GetFileName(string filePath) { //獲取文件的名稱 FileInfo fi = new FileInfo(filePath); return fi.Name; } /// <summary> /// 從文件的絕對(duì)路徑中獲取文件名( 不包含擴(kuò)展名 ) /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static string GetFileNameNoExtension(string filePath) { //獲取文件的名稱 FileInfo fi = new FileInfo(filePath); return fi.Name.Substring(0, fi.Name.LastIndexOf('.')); } /// <summary> /// 從文件的絕對(duì)路徑中獲取擴(kuò)展名 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static string GetExtension(string filePath) { //獲取文件的名稱 FileInfo fi = new FileInfo(filePath); return fi.Extension; } /// <summary> /// 清空文件內(nèi)容 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static void ClearFile(string filePath) { //刪除文件 File.Delete(filePath); //重新創(chuàng)建該文件 CreateFile(filePath); } /// <summary> /// 刪除指定文件 /// </summary> /// <param name="filePath">文件的絕對(duì)路徑</param> public static void DeleteFile(string filePath) { if (IsExistFile(filePath)) { File.Delete(filePath); } } /// <summary> /// 文件是否存在或無權(quán)訪問 /// </summary> /// <param name="path">相對(duì)路徑或絕對(duì)路徑</param> /// <returns>如果是目錄也返回false</returns> public static bool FileIsExist(string path) { return File.Exists(path); } /// <summary> /// 文件是否只讀 /// </summary> /// <param name="fullpath"></param> /// <returns></returns> public static bool FileIsReadOnly(string fullpath) { FileInfo file = new FileInfo(fullpath); if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { return true; } else { return false; } } /// <summary> /// 設(shè)置文件是否只讀 /// </summary> /// <param name="fullpath"></param> /// <param name="flag">true表示只讀,反之</param> public static void SetFileReadonly(string fullpath, bool flag) { FileInfo file = new FileInfo(fullpath); if (flag) { // 添加只讀屬性 file.Attributes |= FileAttributes.ReadOnly; } else { // 移除只讀屬性 file.Attributes &= ~FileAttributes.ReadOnly; } } /// <summary> /// 取文件名 /// </summary> /// <param name="fullpath"></param> /// <returns></returns> public static string GetFileName(string fullpath, bool removeExt) { FileInfo fi = new FileInfo(fullpath); string name = fi.Name; if (removeExt) { name = name.Remove(name.IndexOf('.')); } return name; } /// <summary> /// 取文件創(chuàng)建時(shí)間 /// </summary> /// <param name="fullpath"></param> /// <returns></returns> public static DateTime GetFileCreateTime(string fullpath) { FileInfo fi = new FileInfo(fullpath); return fi.CreationTime; } /// <summary> /// 取文件最后存儲(chǔ)時(shí)間 /// </summary> /// <param name="fullpath"></param> /// <returns></returns> public static DateTime GetLastWriteTime(string fullpath) { FileInfo fi = new FileInfo(fullpath); return fi.LastWriteTime; } /// <summary> /// 創(chuàng)建一個(gè)零字節(jié)臨時(shí)文件 /// </summary> /// <returns></returns> public static string CreateTempZeroByteFile() { return Path.GetTempFileName(); } /// <summary> /// 創(chuàng)建一個(gè)隨機(jī)文件名,不創(chuàng)建文件本身 /// </summary> /// <returns></returns> public static string GetRandomFileName() { return Path.GetRandomFileName(); } /// <summary> /// 判斷兩個(gè)文件的哈希值是否一致 /// </summary> /// <param name="fileName1"></param> /// <param name="fileName2"></param> /// <returns></returns> public static bool CompareFilesHash(string fileName1, string fileName2) { using (HashAlgorithm hashAlg = HashAlgorithm.Create()) { using (FileStream fs1 = new FileStream(fileName1, FileMode.Open), fs2 = new FileStream(fileName2, FileMode.Open)) { byte[] hashBytes1 = hashAlg.ComputeHash(fs1); byte[] hashBytes2 = hashAlg.ComputeHash(fs2); // 比較哈希碼 return (BitConverter.ToString(hashBytes1) == BitConverter.ToString(hashBytes2)); } } } #endregion #region XML文件操作 /// <summary> /// 從XML文件轉(zhuǎn)換為Object對(duì)象類型. /// </summary> /// <param name="path">XML文件路徑</param> /// <param name="type">Object對(duì)象類型</param> /// <returns></returns> public static object LoadObjectFromXml(string path, Type type) { object obj = null; using (StreamReader reader = new StreamReader(path)) { string content = reader.ReadToEnd(); obj = XmlConvertor.XmlToObject(content, type); } return obj; } /// <summary> /// 保存對(duì)象到特定格式的XML文件www.yunjson.com /// </summary> /// <param name="path">XML文件路徑.</param> /// <param name="obj">待保存的對(duì)象</param> public static void SaveObjectToXml(string path, object obj) { string xml = XmlConvertor.ObjectToXml(obj, true); using (StreamWriter writer = new StreamWriter(path)) { writer.Write(xml); } } #endregion } }
原文鏈接:C#文件操作輔助類FileUtil