【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 @   qiutian-hao  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示