1. 程式人生 > >打造一個簡單的TXT文本操作及日誌框架

打造一個簡單的TXT文本操作及日誌框架

默認值 pos 簡單 rst arch rap ++ 項目實現 spa

首先先介紹一下這個項目,該項目實現了文本寫入及讀取,日誌寫入指定文件夾或默認文件夾,日誌數量控制,單個日誌大小控制,通過約定的參數讓用戶可以用更少的代碼解決問題。

1.讀取文本文件方法

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

 1  public static string ReadToString(string path)
 2         {
 3             try
 4             {
 5                 LogLock.EnterReadLock();
 6                 StreamReader sr = new
StreamReader(path, Encoding.Default); 7 StringBuilder sb = new StringBuilder(); 8 string line; 9 while ((line = sr.ReadLine()) != null) 10 { 11 sb.AppendLine(line.ToString()); 12 } 13 sr.Close();
14 sr.Dispose(); 15 return sb.ToString(); 16 } 17 catch (IOException e) 18 { 19 Console.WriteLine(e.ToString()); 20 return null; 21 } 22 finally 23 { 24 LogLock.ExitReadLock();
25 } 26 }

實現解析:

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

(2.創建讀取流StreamReader,依次讀取每一行。

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

2.寫入文本文件方法

(1.創建文本並寫入

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

 1 public static bool CreateWrite(string path, string context)
 2         {
 3             bool b = false;
 4             try
 5             {
 6                 LogLock.EnterWriteLock();
 7                 FileStream fs = new FileStream(path, FileMode.Create);
 8                 //獲得字節數組
 9                 byte[] data = System.Text.Encoding.Default.GetBytes(context);
10                 //開始寫入
11                 fs.Write(data, 0, data.Length);
12                 //清空緩沖區、關閉流
13                 fs.Flush();
14                 fs.Close();
15                 return b;
16             }
17             catch (Exception ex)
18             {
19                 Console.WriteLine(ex.ToString());
20                 return b;
21             }
22             finally
23             {
24                 LogLock.ExitWriteLock();
25             }
26         }

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

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

 1 public static bool WriteAppend(string path, string context)
 2         {
 3             bool b = false;
 4             try
 5             {
 6                 LogLock.EnterWriteLock();
 7                 FileStream fs = new FileStream(path, FileMode.Append);
 8                 StreamWriter sw = new StreamWriter(fs);
 9                 //開始寫入
10                 sw.Write(context);
11                 //清空緩沖區
12                 sw.Flush();
13                 //關閉流
14                 sw.Close();
15                 fs.Close();
16                 return b;
17             }
18             catch (Exception ex)
19             {
20                 Console.WriteLine(ex.ToString());
21                 return b;
22             }
23             finally
24             {
25                 LogLock.ExitWriteLock();
26             }
27         }

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

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

 1 public static bool CreateOrWriteAppendLine(string path, string context)
 2         {
 3             bool b = false;
 4             try
 5             {
 6                 LogLock.EnterWriteLock();
 7                 if (!File.Exists(path))
 8                 {
 9                     FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
10                     StreamWriter sw = new StreamWriter(fs);
11                     long fl = fs.Length;
12                     fs.Seek(fl, SeekOrigin.End);
13                     sw.WriteLine(context);
14                     sw.Flush();
15                     sw.Close();
16                     fs.Close();
17                     b = true;
18                 }
19                 else
20                 {
21                     FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
22                     StreamWriter sw = new StreamWriter(fs);
23                     long fl = fs.Length;
24                     fs.Seek(fl, SeekOrigin.Begin);
25                     sw.WriteLine(context);
26                     sw.Flush();
27                     sw.Close();
28                     fs.Close();
29                     b = true;
30                 }
31                 return b;
32             }
33             catch (Exception ex)
34             {
35                 Console.WriteLine(ex.ToString());
36                 return b;
37             }
38             finally
39             {
40                 LogLock.ExitWriteLock();
41             }
42         }

實現解析:

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

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

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

3.寫入日誌

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

 1 public static void WriteLog(string content, int fileSize = 1, int fileCount = 20, string filePath = "")
 2         {
 3             try
 4             {
 5                 if (!string.IsNullOrWhiteSpace(filePath))
 6                 {
 7                     logPath = filePath;
 8                 }
 9                 LogLock.EnterWriteLock();
10                 logPath = logPath.Replace("file:\\", "");//這裏為了兼容webapi的情況
11                 string dataString = DateTime.Now.ToString("yyyy-MM-dd");
12                 string path = logPath + "\\MyLog";
13                 if (!Directory.Exists(path))
14                 {
15                     Directory.CreateDirectory(path);
16                     path += "\\";
17                     path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
18                     FileStream fs = new FileStream(path, FileMode.Create);
19                     fs.Close();
20                 }
21                 else
22                 {
23                     int x = System.IO.Directory.GetFiles(path).Count();
24                     path += "\\";
25                     Dictionary<string, DateTime> fileCreateDate = new Dictionary<string, DateTime>();
26                     string[] filePathArr = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly);
27                     if (filePathArr.Length == 0)
28                     {
29                         string sourceFilePath = path;
30                         path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
31                         FileStream fs = new FileStream(path, FileMode.Create);
32                         fs.Close();
33                         filePathArr = Directory.GetFiles(sourceFilePath, "*.txt", SearchOption.TopDirectoryOnly);
34                     }
35                     for (int i = 0; i < filePathArr.Length; i++)
36                     {
37                         FileInfo fi = new FileInfo(filePathArr[i]);
38                         fileCreateDate[filePathArr[i]] = fi.CreationTime;
39                     }
40                     fileCreateDate = fileCreateDate.OrderBy(f => f.Value).ToDictionary(f => f.Key, f => f.Value);
41                     FileInfo fileInfo = new FileInfo(fileCreateDate.Last().Key);
42                     if (fileInfo.Length < 1024 * 1024 * fileSize)
43                     {
44                         path = fileCreateDate.Last().Key;
45                     }
46                     else
47                     {
48                         path += DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
49                         FileStream fs = new FileStream(path, FileMode.Create);
50                         fs.Close();
51                     }
52                     if (x > fileCount)
53                     {
54                         File.Delete(fileCreateDate.First().Key);
55                     }
56 
57                 }
58                 FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.Write);
59                 StreamWriter sw = new StreamWriter(fs2);
60                 long fl = fs2.Length;
61                 fs2.Seek(fl, SeekOrigin.Begin);
62                 sw.WriteLine(DateTime.Now.ToString("hh:mm:ss") + "---> " + content);
63                 sw.Flush();
64                 sw.Close();
65                 fs2.Close();
66             }
67             catch (Exception ex)
68             {
69                 Console.WriteLine(ex.ToString());
70             }
71             finally
72             {
73                 LogLock.ExitWriteLock();
74             }
75 
76         }

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

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

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

(3.寫入到指定文件。

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

項目框架就介紹到這裏吧,後期還會將功能擴展,不多說了源碼地址:

https://download.csdn.net/download/silverbutter/10569972。

打造一個簡單的TXT文本操作及日誌框架