这篇文章主要介绍C#如何实现一个简单实用的TXT文本操作及日志框架,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
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, 0, 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 = 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.检测文件目录是否已存在,不存在则创建目录并创建日志文件,存在就判断文件数量和大小,文件大小超过设置的值或默认值就新建一个文本,文件数量超过默认值或设置值就删除最早的一个文件。
(3.写入到指定文件。
(4.完成释放资源。并解锁。
问题汇总:
bug1:程序包中读取txt可能出现乱码,读取流中改一下把默认改为Encoding.UTF8应该就可以了。
以上是“C#如何实现一个简单实用的TXT文本操作及日志框架”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。