C#如何實現一個簡單實用的TXT文本操作及日志框架-創(chuàng)新互聯

這篇文章主要介紹C#如何實現一個簡單實用的TXT文本操作及日志框架,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

成都創(chuàng)新互聯長期為上千余家客戶提供的網站建設服務,團隊從業(yè)經驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯網生態(tài)環(huán)境。為天鎮(zhèn)企業(yè)提供專業(yè)的做網站、網站設計,天鎮(zhèn)網站改版等技術服務。擁有10多年豐富建站經驗和眾多成功案例,為您定制開發(fā)。

1.讀取文本文件方法

使用:JIYUWU.TXT.TXTHelper.ReadToString(“文件物理路徑”)

public static string ReadToString(string path)
 {
  try
  {
  LogLock.EnterReadLock();
  StreamReader sr = new StreamReader(path, Encoding.UTF8);
  StringBuilder sb = new StringBuilder();
  string line;
  while ((line = sr.ReadLine()) != null)
  {
   sb.AppendLine(line.ToString());
  }
  sr.Close();
  sr.Dispose();
  return sb.ToString();
  }
  catch (IOException e)
  {
  Console.WriteLine(e.ToString());
  return null;
  }
  finally
  {
  LogLock.ExitReadLock();
  }
 }

實現解析:

(1.為防止任務讀取當我們進行讀取時需要添加讀取鎖保證可以依次讀取,否則可能出現被占用異常。

(2.創(chuàng)建讀取流StreamReader(注意:由于會出現亂碼這里要改一下把默認改為Encoding.UTF8),依次讀取每一行。

(3.讀取完成釋放資源。并解鎖。

2.寫入文本文件方法

(1.創(chuàng)建文本并寫入

使用:JIYUWU.TXT.TXTHelper.CreateWrite(“文件物理路徑”,“文本內容”)

public static bool CreateWrite(string path, string context)
 {
  bool b = false;
  try
  {
  LogLock.EnterWriteLock();
  FileStream fs = new FileStream(path, FileMode.Create);
  //獲得字節(jié)數組
  byte[] data = System.Text.Encoding.Default.GetBytes(context);
  //開始寫入
  fs.Write(data, 0, data.Length);
  //清空緩沖區(qū)、關閉流
  fs.Flush();
  fs.Close();
  return b;
  }
  catch (Exception ex)
  {
  Console.WriteLine(ex.ToString());
  return b;
  }
  finally
  {
  LogLock.ExitWriteLock();
  }
 }

(2.在文本文件末尾追加寫入

使用:JIYUWU.TXT.TXTHelper.WriteAppend(“文件物理路徑”,“文本內容”)

public static bool WriteAppend(string path, string context)
 {
  bool b = false;
  try
  {
  LogLock.EnterWriteLock();
  FileStream fs = new FileStream(path, FileMode.Append);
  StreamWriter sw = new StreamWriter(fs);
  //開始寫入
  sw.Write(context);
  //清空緩沖區(qū)
  sw.Flush();
  //關閉流
  sw.Close();
  fs.Close();
  return b;
  }
  catch (Exception ex)
  {
  Console.WriteLine(ex.ToString());
  return b;
  }
  finally
  {
  LogLock.ExitWriteLock();
  }
 }

(3.自動判斷換行追加或創(chuàng)建文本

使用:JIYUWU.TXT.TXTHelper.CreateOrWriteAppendLine(“文件物理路徑”,“文本內容”)

public static bool CreateOrWriteAppendLine(string path, string context)
 {
  bool b = false;
  try
  {
  LogLock.EnterWriteLock();
  if (!File.Exists(path))
  {
   FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
   StreamWriter sw = new StreamWriter(fs);
   long fl = fs.Length;
   fs.Seek(fl, SeekOrigin.End);
   sw.WriteLine(context);
   sw.Flush();
   sw.Close();
   fs.Close();
   b = true;
  }
  else
  {
   FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
   StreamWriter sw = new StreamWriter(fs);
   long fl = fs.Length;
   fs.Seek(fl, SeekOrigin.Begin);
   sw.WriteLine(context);
   sw.Flush();
   sw.Close();
   fs.Close();
   b = true;
  }
  return b;
  }
  catch (Exception ex)
  {
  Console.WriteLine(ex.ToString());
  return b;
  }
  finally
  {
  LogLock.ExitWriteLock();
  }
 }

實現解析:

(1)為防止多任務讀取當我們進行讀取時需要添加讀取鎖保證可以依次寫入,否則可能出現被占用異常。

(2)創(chuàng)建文本流FileStream及寫入流StreamWriter,直接進行數據寫入。

(3)讀取完成釋放資源。并解鎖。

3.寫入日志

使用:JIYUWU.TXT.TXTHelper.WriteLog(“文本內容”,“單個文件大?。ㄟx填默認1M)”,“目錄下文件數量(選填默認20個)”,“輸出目錄(選填默認bin文件下)”)

public static void WriteLog(string content, int fileSize = 1, int fileCount = 20, string filePath = "")
 {
  try
  {
  if (!string.IsNullOrWhiteSpace(filePath))
  {
   logPath = filePath;
  }
  LogLock.EnterWriteLock();
  logPath = logPath.Replace("file:\\", "");//這里為了兼容webapi的情況
  string dataString = DateTime.Now.ToString("yyyy-MM-dd");
  string path = logPath + "\\MyLog";
  if (!Directory.Exists(path))
  {
   Directory.CreateDirectory(path);
   path += "\\";
   path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
   FileStream fs = new FileStream(path, FileMode.Create);
   fs.Close();
  }
  else
  {
   int x = System.IO.Directory.GetFiles(path).Count();
   path += "\\";
   Dictionary<string, DateTime> fileCreateDate = new Dictionary<string, DateTime>();
   string[] filePathArr = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly);
   if (filePathArr.Length == 0)
   {
   string sourceFilePath = path;
   path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
   FileStream fs = new FileStream(path, FileMode.Create);
   fs.Close();
   filePathArr = Directory.GetFiles(sourceFilePath, "*.txt", SearchOption.TopDirectoryOnly);
   }
   for (int i = 0; i < filePathArr.Length; i++)
   {
   FileInfo fi = new FileInfo(filePathArr[i]);
   fileCreateDate[filePathArr[i]] = fi.CreationTime;
   }
   fileCreateDate = fileCreateDate.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value);
   FileInfo fileInfo = new FileInfo(fileCreateDate.Last().Key);
   if (fileInfo.Length < 1024 * 1024 * fileSize)
   {
   path = fileCreateDate.Last().Key;
   }
   else
   {
   path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
   FileStream fs = new FileStream(path, FileMode.Create);
   fs.Close();
   }
   if (x > fileCount)
   {
   File.Delete(fileCreateDate.First().Key);
   }

  }
  FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.Write);
  StreamWriter sw = new StreamWriter(fs2);
  long fl = fs2.Length;
  fs2.Seek(fl, SeekOrigin.Begin);
  sw.WriteLine(DateTime.Now.ToString("hh:mm:ss") + "---> " + content);
  sw.Flush();
  sw.Close();
  fs2.Close();
  }
  catch (Exception ex)
  {
  Console.WriteLine(ex.ToString());
  }
  finally
  {
  LogLock.ExitWriteLock();
  }

 }

實現解析(以全部默認參數為例說明):

(1.為防止多任務進行操作,于是對文檔加一個寫入鎖,否則可能出現被占用異常。

(2.檢測文件目錄是否已存在,不存在則創(chuàng)建目錄并創(chuàng)建日志文件,存在就判斷文件數量和大小,文件大小超過設置的值或默認值就新建一個文本,文件數量超過默認值或設置值就刪除最早的一個文件。

(3.寫入到指定文件。

(4.完成釋放資源。并解鎖。

問題匯總:

bug1:程序包中讀取txt可能出現亂碼,讀取流中改一下把默認改為Encoding.UTF8應該就可以了。

以上是“C#如何實現一個簡單實用的TXT文本操作及日志框架”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯成都網站設計公司行業(yè)資訊頻道!

另外有需要云服務器可以了解下創(chuàng)新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

文章題目:C#如何實現一個簡單實用的TXT文本操作及日志框架-創(chuàng)新互聯
網站URL:http://muchs.cn/article18/cecsgp.html

成都網站建設公司_創(chuàng)新互聯,為您提供ChatGPT標簽優(yōu)化、手機網站建設、網站營銷、做網站、動態(tài)網站

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯

微信小程序開發(fā)