首先先介绍一下这个项目,该项目实现了文本写入及读取,日志写入指定文件夹或默认文件夹,日志数量控制,单个日志大小控制,通过约定的参数让用户可以用更少的代码解决问题。

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.创建读取流StreamReader(注意:由于会出现乱码这里要改一下把默认改为Encoding.UTF8),依次读取每一行。

(3.读取完成释放资源。并解锁。

2.写入文本文件方法

(1.创建文本并写入

使用: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);
//获得字节数组
byte[] data = System.Text.Encoding.Default.GetBytes(context);
//开始写入
fs.Write(data, , data.Length);
//清空缓冲区、关闭流
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);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
return b;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return b;
}
finally
{
LogLock.ExitWriteLock();
}
}

(3.自动判断换行追加或创建文本

使用: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)创建文本流FileStream及写入流StreamWriter,直接进行数据写入。

(3)读取完成释放资源。并解锁。

3.写入日志

使用:JIYUWU.TXT.TXTHelper.WriteLog(“文本内容”,“单个文件大小(选填默认1M)”,“目录下文件数量(选填默认20个)”,“输出目录(选填默认bin文件下)”)

 public static void WriteLog(string content, int fileSize = , int fileCount = , 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 == )
{
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 = ; 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 < * * 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.检测文件目录是否已存在,不存在则创建目录并创建日志文件,存在就判断文件数量和大小,文件大小超过设置的值或默认值就新建一个文本,文件数量超过默认值或设置值就删除最早的一个文件。

(3.写入到指定文件。

(4.完成释放资源。并解锁。

项目框架就介绍到这里吧,后期还会将功能扩展,不多说了源码地址:

https://download.csdn.net/download/silverbutter/10569972 (可能存在没有测到的bug,出现的问题可以反馈给我,谢谢您的支持)。

问题汇总:

bug1:程序包中读取txt可能出现乱码,读取流中改一下把默认改为Encoding.UTF8应该就可以了。

打造一个简单实用的的TXT文本操作及日志框架的更多相关文章

  1. 收藏收藏:时隔一年,你关注的打造一个实用的TXT文本操作及日志框架,我们开源了,不再为程序写日志发愁(也支持.net core哦)

    记得做这个框架是在2018年刚接触.net core的时候,那个时候为了能够专心的研究我开始不写博客了,但是学有所成并在公司运用了近一年的时间了,决定回来和各位分享我们所掌握的那星星点点的知识,希望可 ...

  2. 一个简单的代码生成器(T4文本模板运用)

    说要写这篇文章有一段时间了,但因为最近各方面的压力导致心情十二分的不好,下班后往往都洗洗睡了.今天痛定思痛,终于把这件拖了很久的事做了.好,不废话了,现在看看"一个简单的代码生成器" ...

  3. [.NET] 一步步打造一个简单的 MVC 网站 - BooksStore(一)

    一步步打造一个简单的 MVC 网站 - BooksStore(一) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore 简介 主 ...

  4. [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(二)

    一步步打造一个简单的 MVC 电商网站 - BooksStore(二) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore 前: ...

  5. [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(三)

    一步步打造一个简单的 MVC 电商网站 - BooksStore(三) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore &l ...

  6. [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(四)

    一步步打造一个简单的 MVC 电商网站 - BooksStore(四) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore &l ...

  7. [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(一)

    一步步打造一个简单的 MVC 电商网站 - BooksStore(一) 本系列的 GitHub地址:https://github.com/liqingwen2015/Wen.BooksStore &l ...

  8. [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(一) (转)

    http://www.cnblogs.com/liqingwen/p/6640861.html 一步步打造一个简单的 MVC 电商网站 - BooksStore(一) 本系列的 GitHub地址:ht ...

  9. LogCook 一个简单实用的Android日志管理工具

    众所周知,日志的管理是软件系统很重要的一部分,千万不可忽略其重要性.完整的日志将会在系统维护中起着异常重要的作用,就好像磨刀不误砍柴工一样,日志就像对系统进行分析的工具,工具便捷了,对系统分析起来就能 ...

随机推荐

  1. class文件格式说明

    java代码编译成class文件之后,class文件里面的语法是什么样的,他的数据类型是什么以及如何存放的?? class也是一种语言写的,只不过和我们的java语法不同而已. class文件就是把j ...

  2. 关于phpmailer邮件发送

    今天有个需求,要把phpmailer集成到框架里面 所以我去官方下载了 phpmail5.2.6 地址在 https://github.com/PHPMailer/PHPMailer/releases ...

  3. 利用Nginx rewrite规则实现域名显性转发

    体验更优排版请移步原文:http://blog.kwin.wang/website/nginx-rewrite-realize-domain-forward.html 自己的blog域名最开始用的vb ...

  4. 1 数据库开发--MySQL介绍

    1.数据库管理软件 C/S 并发.锁 :SQL语句.语法 基本管理和语法学习 一.介绍: mysql数据库管理软件: 套接字:服务端,客户端:客户端可访问服务端得数据 1.支持并发:操作得是共享得数据 ...

  5. python传值&值引用

    [python传值&值引用] 和其他语言不一样,传递参数的时候,python不允许程序员选择采用传值还是传引用.Python参数传递采用的肯定是“传对象引用”的方式.实际上,这种方式相当于传值 ...

  6. spring 控制反转与依赖注入原理-学习笔记

    在Spring中有两个非常重要的概念,控制反转和依赖注入:控制反转将依赖对象的创建和管理交由Spring容器,而依赖注入则是在控制反转的基础上将Spring容器管理的依赖对象注入到应用之中: 所谓依赖 ...

  7. Linux进程之Fork函数

    Fork()函数 1.所需头文件: #include <unistd.h> #include<sys/types.h> 2.函数定义 pid_t fork( void ); p ...

  8. Visual Studio 2013 boost

    E:\Visual Studio 2013\install\VC\bin\amd64>E:\IFC\boost_1_56_0_vs2013'E:\IFC\boost_1_56_0_vs2013' ...

  9. 6-Collision-hdu5114(小球碰撞)

    Collision Time Limit: 15000/15000 MS (Java/Others)    Memory Limit: 512000/512000 K (Java/Others)Tot ...

  10. 字符编码codecs模块(读写文件)

    python对多国语言的处理是支持的很好的,它可以处理现在任意编码的字符,这里深入的研究一下python对多种不同语言的处理.有一点需要清楚的是,当python要做编码转换的时候,会借助于内部的编码, ...