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 }