C#讀取寫入日志文本LogHelper類庫(kù)
一個(gè)高效便捷的操作日志文件的幫助類庫(kù),將錄入的內(nèi)容寫入文件,
可自定義生成規(guī)則和保存路徑
在記錄日志時(shí),可以方便的調(diào)用
使用方法:
FileLogHelper.logContent.Add("日志內(nèi)容");
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("日志內(nèi)容");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()
{
//將錄入的內(nèi)容寫入文件
string content = ReaderText();
//創(chuàng)建文件流
FileStream myfs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
//創(chuàng)建寫入器
StreamWriter mySw = new StreamWriter(myfs);
foreach (string log in logContent)
{
content = log "\r\n";
}
mySw.WriteLine(content);
//關(guān)閉寫入器
mySw.Close();
//關(guān)閉文件流
myfs.Close();
logContent.Clear(); // 清理日志
}
/// <summary>
/// 讀取日志文本
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string ReaderText()
{
if (!Directory.Exists(LogPath))
Directory.CreateDirectory(LogPath);
//創(chuàng)建文件流
FileStream myfs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);
//創(chuàng)建讀取器
StreamReader mySr = new StreamReader(myfs);
//讀取文件所有內(nèi)容
string content = mySr.ReadToEnd();
//關(guān)閉讀取器
mySr.Close();
//關(guān)閉文件流
myfs.Close();
return content;
}
}
}
原文鏈接:C#讀取寫入日志文本LogHelper類庫(kù)