首先先介绍一下这个项目,该项目实现了文本写入及读取,日志写入指定文件夹或默认文件夹,日志数量控制,单个日志大小控制,通过约定的参数让用户可以用更少的代码解决问题。
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。
原文地址:https://www.cnblogs.com/jiyuwu/p/9383193.html