C# 寫入文字到Txt文件,用來記錄日志


  1. 復制代碼直接使用
    1. //簡潔版
          public static void AddLgoToTXT(string logstring)
              {
                  string path = AppDomain.CurrentDomain.BaseDirectory + "operalog.txt";
                  if (!System.IO.File.Exists(path))
                  {
                      FileStream stream = System.IO.File.Create(path);
                      stream.Close();
                      stream.Dispose();
                  }
                  using (StreamWriter writer = new StreamWriter(path, true))
                  {
                      writer.WriteLine(logstring);
                  }
              }
        //帶自動刪除版
              
              public static void Logtest(string logstring)
              {
                  try
                  {
                      string path = AppDomain.CurrentDomain.BaseDirectory + "operalog.txt";
                      //判斷文件是否存在,沒有則創建。
                      if (!System.IO.File.Exists(path))
                      {
                          FileStream stream = System.IO.File.Create(path);
                          stream.Close();
                          stream.Dispose();
                      }
      
                      //寫入日志
                      using (StreamWriter writer = new StreamWriter(path, true))
                      {
                          writer.WriteLine(logstring);                                
                      }
      
                      long size = 0;
      
                      //獲取文件大小
                      using (FileStream file = System.IO.File.OpenRead(path))
                      {
                           size = file.Length;//文件大小。byte
                      }
      
                      //判斷日志文件大於2M,自動刪除。
                      if (size > (1024 * 4 * 512))
                      {                  
                          System.IO.File.Delete(path);
                      }
                  }
                  catch
                  {
      
                  }
              }

       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM