这篇文章主要为大家详细介绍了C#分天记录日记类的简单示例,具有一定的参考价值,可以用来参考一下。
感兴趣C#分天记录日记类的简单示例的小伙伴,下面一起跟随四海网的小编罗X来看看吧。<br>
public class LogHelp
{
private static object Block = new object();
#region 记录日志
/// <summary>
/// 记录日志
/// </summary>
/// <param name="msg"></param>
public static void WriteLog(string msg)
{
//string path = @"C:\log.txt";
lock (Block)
{
string filename = DateTime.Now.ToString("yyyyMMdd");
//该日志文件会存在windows服务程序目录下
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + filename + ".txt";
#region 删除前30天的日记
string sYue = DateTime.Now.AddDays(-30).ToString("yyyyMMdd");
DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + sYue + ".txt");
#endregion
if (!Directory.Exists(path))//如果不存在,则创建
{
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\");
}
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
FileStream fs;
fs = File.Create(path);
fs.Close();
}
else if (file.Length > 30 * 1000 * 1000)
{
file.Delete();
FileStream fs;
fs = File.Create(path);
fs.Close();
}
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + " " + msg);
}
}
}
}
public static void WriteLog2(string msg)
{
//string path = @"C:\log.txt";
lock (Block)
{
//该日志文件会存在windows服务程序目录下
string path = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt";
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
FileStream fs;
fs = File.Create(path);
fs.Close();
}
else if (file.Length > 30 * 1000 * 1000)
{
file.Delete();
FileStream fs;
fs = File.Create(path);
fs.Close();
}
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + " " + msg);
}
}
}
}
#endregion
public static void DeleteFile(string path)
{
if (File.Exists(path))//判断文件是不是存在
{
File.Delete(path);//如果存在则删除
}
}
}
本文来自:http://www.q1010.com/194/16378-0.html
注:关于C#分天记录日记类的简单示例的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:类
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。