国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C# > 正文

C#實(shí)現(xiàn)一個(gè)簡(jiǎn)單實(shí)用的TXT文本操作及日志框架詳解

2019-10-29 21:01:16
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

前言

首先先介紹一下這個(gè)項(xiàng)目,該項(xiàng)目實(shí)現(xiàn)了文本寫入及讀取,日志寫入指定文件夾或默認(rèn)文件夾,日志數(shù)量控制,單個(gè)日志大小控制,通過(guò)約定的參數(shù)讓用戶可以用更少的代碼解決問(wèn)題。

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();  } }

實(shí)現(xiàn)解析:

(1.為防止任務(wù)讀取當(dāng)我們進(jìn)行讀取時(shí)需要添加讀取鎖保證可以依次讀取,否則可能出現(xiàn)被占用異常。

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

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

2.寫入文本文件方法

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

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

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

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

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

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);  //開(kāi)始寫入  sw.Write(context);  //清空緩沖區(qū)  sw.Flush();  //關(guān)閉流  sw.Close();  fs.Close();  return b;  }  catch (Exception ex)  {  Console.WriteLine(ex.ToString());  return b;  }  finally  {  LogLock.ExitWriteLock();  } }

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

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

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();  } }

實(shí)現(xiàn)解析:

(1)為防止多任務(wù)讀取當(dāng)我們進(jìn)行讀取時(shí)需要添加讀取鎖保證可以依次寫入,否則可能出現(xiàn)被占用異常。

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

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

3.寫入日志

使用:JIYUWU.TXT.TXTHelper.WriteLog(“文本內(nèi)容”,“單個(gè)文件大小(選填默認(rèn)1M)”,“目錄下文件數(shù)量(選填默認(rèn)20個(gè))”,“輸出目錄(選填默認(rèn)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();  } }

實(shí)現(xiàn)解析(以全部默認(rèn)參數(shù)為例說(shuō)明):

(1.為防止多任務(wù)進(jìn)行操作,于是對(duì)文檔加一個(gè)寫入鎖,否則可能出現(xiàn)被占用異常。

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

(3.寫入到指定文件。

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

項(xiàng)目框架就介紹到這里吧,后期還會(huì)將功能擴(kuò)展,不多說(shuō)了源碼地址:

(可能存在沒(méi)有測(cè)到的bug,出現(xiàn)的問(wèn)題可以反饋給我,謝謝您的支持)。

問(wèn)題匯總:

bug1:程序包中讀取txt可能出現(xiàn)亂碼,讀取流中改一下把默認(rèn)改為Encoding.UTF8應(yīng)該就可以了。

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VEVB武林網(wǎng)的支持。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到c#教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 司法| 阜平县| 彭州市| 疏勒县| 沙田区| 上高县| 财经| 兴化市| 阿图什市| 连州市| 松潘县| 华池县| 托克逊县| 松溪县| 阳曲县| SHOW| 视频| 松滋市| 松阳县| 房产| 扎兰屯市| 灵武市| 芜湖县| 濮阳县| 合阳县| 南宫市| 佳木斯市| 西平县| 曲沃县| 汪清县| 沛县| 高淳县| 佳木斯市| 浙江省| 仁布县| 威海市| 株洲市| 青岛市| 平舆县| 盖州市| 白城市|