【C#】实现读写文件

 /// <summary>
 /// 同步锁
 /// </summary>
 private static readonly object syncRoot = new object();
 /// <summary>
 /// 读同步锁
 /// </summary>
 private static readonly object syncReadRoot = new object();

 /// <summary>
 /// 覆盖写文件信息
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="message"></param>
 /// <returns></returns>
 public static bool WriteFileCover(string filePath,string message)
 { 
     bool bRet=false;
     try
     {
         lock (syncRoot)
         {
             //写入文件
             FileStream fs;
             StreamWriter sw;
             fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
             sw = new StreamWriter(fs);
             sw.Write(message);//开始写入值
             sw.Close();//关闭写入流
             fs.Close();//关闭文件流

             bRet = true;
         }
     }
     catch (Exception ex)
     {
         bRet = false;
     }
     return bRet;
 }
 /// <summary>
 /// 追加写文件信息
 /// </summary>
 /// <param name="filePath"></param>
 /// <param name="message"></param>
 /// <returns></returns>
 public static bool WriteFileAppend(string filePath, string message)
 {
     bool bRet = false;
     try
     {
         lock (syncRoot)
         {
             //写入文件
             FileStream fs;
             StreamWriter sw;
             if (!File.Exists(filePath))
             {
                 fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                 sw = new StreamWriter(fs);
                 sw.Write(message);//开始写入值
             }
             else
             {
                 fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
                 sw = new StreamWriter(fs);
                 sw.Write(message);//开始写入值
             }
             sw.Close();//关闭写入流
             fs.Close();//关闭文件流
             bRet = true;
         }
     }
     catch (Exception ex)
     {
        bRet = false;
     }
     return bRet;
 }
 /// <summary>
 /// 读取文件信息
 /// </summary>
 /// <param name="filePath"></param>
 /// <returns></returns>
 public static string ReadFile(string filePath)
 {
     string message = "";
     lock (syncReadRoot)
     {
         StreamReader? sr = null;
         try
         {
             if (!File.Exists(filePath))
             {
                 return message;
             }
             sr = File.OpenText(filePath);
             string? nextLine;
             while ((nextLine = sr.ReadLine()) != null)
             {
                 message += nextLine;
             }
             sr?.Close();
         }
         catch (Exception ex)
         {
             sr?.Close();
         }
     }
     return message;
 }
posted @ 2024-08-13 09:04  qiutian-hao  阅读(4)  评论(0编辑  收藏  举报