1. 程式人生 > 其它 >【C# .NET 工具類 】二、文字檔案讀取與寫入

【C# .NET 工具類 】二、文字檔案讀取與寫入

1.讀取文字檔案

 1 public partial class TextFile
 2 {
 3     /// <summary>
 4     /// 讀取文字檔案
 5     /// </summary>
 6     /// <param name="filePath">被讀取檔案的路徑</param>
 7     /// <returns></returns>
 8     public static string Read(string filePath)
 9     {
10         try
11         {
12             if
(!File.Exists(filePath)) 13 { 14 return string.Empty; 15 } 16 17 return File.ReadAllText(filePath); 18 } 19 catch (Exception ex) 20 { 21 throw ex; 22 } 23 } 24 }

2.寫入文字檔案

 1 public partial class TextFile
2 { 3 /// <summary> 4 /// 寫入文字檔案 5 /// </summary> 6 /// <param name="filePath">檔案路徑,包括檔名</param> 7 /// <param name="contact">需要寫入的內容</param> 8 public static void Write(string filePath,string contact) 9 { 10 try 11 { 12 if
(string.IsNullOrWhiteSpace(filePath)) 13 { 14 throw new Exception("filePath is empty"); 15 } 16 17 string fileDirectory = Path.GetDirectoryName(filePath); 18 if (!Directory.Exists(fileDirectory)) 19 { 20 Directory.CreateDirectory(fileDirectory); 21 } 22 23 FileStream fs = new FileStream(filePath, FileMode.Create); 24 StreamWriter sw = new StreamWriter(fs); 25 sw.Write((File.Exists(filePath) ? "\n" : "") + contact); 26 sw.Flush(); 27 sw.Close(); 28 fs.Close(); 29 } 30 catch (Exception ex) 31 { 32 throw; 33 } 34 } 35 }