C#读取写入日志文本LogHelper类库
一个高效便捷的操作日志文件的帮助类库,将录入的内容写入文件,
可自定义生成规则和保存路径
在记录日志时,可以方便的调用
使用方法:
FileLogHelper.logContent.Add("日志内容");
FileLogHelper.WriterToText();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Configuration;
namespace AutoHome.Fil
{
/// <summary>
/// 使用方法: FileLogHelper.logContent.Add("日志内容");FileLogHelper.WriterToText();
/// </summary>
public class FileLogHelper
{
static string LogPath = ConfigurationManager.AppSettings["LogPath"].ToString();
static string filePath = LogPath + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
public static List<string> logContent = new List<string>();
/// <summary>
/// 写入日志文本
/// </summary>
/// <param name="path"></param>
/// <param name="content"></param>
public static void WriterToText()
{
//将录入的内容写入文件
string content = ReaderText();
//创建文件流
FileStream myfs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
//创建写入器
StreamWriter mySw = new StreamWriter(myfs);
foreach (string log in logContent)
{
content += log + "\r\n";
}
mySw.WriteLine(content);
//关闭写入器
mySw.Close();
//关闭文件流
myfs.Close();
logContent.Clear(); // 清理日志
}
/// <summary>
/// 读取日志文本
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string ReaderText()
{
if (!Directory.Exists(LogPath))
Directory.CreateDirectory(LogPath);
//创建文件流
FileStream myfs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
//创建读取器
StreamReader mySr = new StreamReader(myfs);
//读取文件所有内容
string content = mySr.ReadToEnd();
//关闭读取器
mySr.Close();
//关闭文件流
myfs.Close();
return content;
}
}
}