我们在做程序时日志文件是个十分重要的功能,可以报我们处理程序跟踪,错误处理等等。但是由于wince系统的功能限制很多高级功能都不能用,这个时候我们用txt文件来存储日志是个不错的选择。但是我们也不能一直的去写入而不删除,这样的话就会导致文件越来越大。这样的话就得不偿失了,所以我们还要做定期的删除,这样才能保证性能,现在我把代码分享给大家。希望对大家有用
using System;
using System.Linq;
using System.Collec
tions.Generic;
using System.Text;
using System.IO;
namespace scy.MySystem
{
class WriteLog
{
///
/// 写日志
///
///
内容
///
路径(相对hycom下的文件夹路径)
///
日志名(默认yyyy-MM-dd.txt)
private void MyWriteDRALog(string strMsg, string strPath, string fileName)
{
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\Log\" + strPath;
if (!path.EndsWith("\") || !path.EndsWith("/"))
{
path += "\";
}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
DeleteLog(path);
if (fileName == "")
{
fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
}
if (!fileName.EndsWith(".txt"))
{
fileName += ".txt";
}
try
{
//string fileName =DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StreamWriter sw = new StreamWriter(path + fileName, true, Encoding.GetEncoding("GB2312"));
// StreamWriter sw = File.a(path + fileName);
sw.WriteLine("{0}:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), strMsg);
//sw.WriteLine("nr");
sw.Flush();
sw.Close();
}
catch { }
}
///
/// 写日志
///
///
内容
///
路径(相对hycom下的文件夹路径)
public void MyWriteDRALog(string strMsg, string strPath)
{
string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
switch (strPath)
{
case "System":
MyWriteDRALog(strMsg, strPath, fileName);
break;
case "MyDB":
if (MyVariable.MySystem.storeLog == true)
{
MyWriteDRALog(strMsg, strPath, fileName);
}
break;
case "UPPC":
if (MyVariable.MySystem.PCSerrialLog == true)
{
MyWriteDRALog(strMsg, strPath, fileName);
}
break;
}
}
///
/// 定期删除日志
///
///
日志路径
private void DeleteLog(string strPath)
{
if (Directory.Exists(strPath))
{
DirectoryInfo dinfor = new DirectoryInfo(strPath);
FileInfo[] files = dinfor.GetFiles();
foreach (FileInfo file in files)
{
try
{
//删除创建日志日期是1个月前的日志
if (DateTime.Compare(file.CreationTime.AddDays(14), DateTime.Now) < 0)
{
file.Delete();
}
//删除最后修改日志日期是1个月前的日志
if (DateTime.Compare(file.LastWriteTime.AddDays(14), DateTime.Now) < 0)
{
file.Delete();
}
//删除日志名称日期是1个月前的日志
if (DateTime.Compare(Convert.ToDateTime(file.Name.Substring(0, 10)), DateTime.Now.AddDays(-14)) < 0)
{
file.Delete();
}
}
catch
{
continue;
}
}
}
}
}
}