點選檢視程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
public static class setLog
{
/// <summary>
/// 建立txt,並寫入
/// </summary>
/// <param name="logmsg">要寫入的資訊</param>
public static void SetLogTx(string logmsg)
{
//檔名
DateTime dt = DateTime.Now;
string path = System.AppDomain.CurrentDomain.BaseDirectory;
string filename = dt.ToString("yyyy-MM-dd") + "_log.txt";
//沒有則建立,同一天不建立多個
FileStream fs;
if (!File.Exists(path + filename))
{
fs = new FileStream(path + filename, FileMode.Create, FileAccess.Write);
}
else
{
fs = new FileStream(path + filename, FileMode.Open, FileAccess.Write);
}
//追加寫入
StreamWriter sw = new StreamWriter(fs);
long fl = fs.Length;
fs.Seek(fl, SeekOrigin.Begin);
sw.WriteLine(DateTime.Now.ToString() + " _S:_____" + logmsg + "_____End.\n");//開始寫入值
//結束
sw.Close();
fs.Close();
}
/// <summary>
/// 刪除大於7天的log文件
/// </summary>
public static void deleteLogTxt()
{
string filePath = System.AppDomain.CurrentDomain.BaseDirectory;
string[] files = Directory.GetFiles(filePath, "*_log.txt");
foreach (var file in files)
{
FileInfo fi = new FileInfo(file);
if ((DateTime.Now - fi.LastWriteTime).TotalDays > 7) //fi.CreationTime
{
fi.Delete();
}
else break;
}
}
}