111,126
社区成员
发帖
与我相关
我的任务
分享
public partial class RecordLog
{
public FileStream fs = null;
public StreamWriter sw = null;
public string Dir = @"C:\DEVICE\NOTIFY";
public static RecordLog instance;
/// <summary>
/// 读取或者新建日志文件
/// </summary>
public RecordLog()
{
try
{
if (!Directory.Exists(Dir))// 目录不存在,新建目录
{
Directory.CreateDirectory(Dir);
}
DeleteFile();
fs = new FileStream(
Dir + "\\" + GetFileName(),
FileMode.Append,
FileAccess.Write,
FileShare.ReadWrite);
fs.Seek(0, System.IO.SeekOrigin.End);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
}
catch (Exception ex)
{
MessageBox.Show("Exception" + ex.Message);
if (sw != null)
{
sw.Close();
sw = null;
}
if (fs != null)
{
fs.Close();
fs = null;
}
}
}
public static RecordLog GetInstance()
{
if (instance == null)
{
instance = new RecordLog();
}
return instance;
}
public string GetFileName()//根据不同月份,新建不同的日志文件
{
。。。。。。
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="info">需要写的日志信息</param>
public void WriteLog(string info)
{
DateTime dt = DateTime.Now;
sw.WriteLine("{0}{1}",dt ,info);
sw.Flush();
}
public void CloseLog()
{
if (sw != null)
{
sw.Close();
sw = null;
}
if (fs != null)
{
fs.Close();
fs = null;
}
}
public void DeleteFile()
{
try
{
if (!File.Exists(Dir + "\\" + GetFileName())) //文件不存在,直接跳过
return;
DateTime createTime = File.GetLastWriteTime(Dir + "\\" + GetFileName());//获取文件的最后修改时间,如果获取文件的最后创建时间,会有问题
DateTime nowTime = DateTime.Now;
//删除文件
if ((createTime.Year != nowTime.Year) && (createTime.Month == nowTime.Month))
{
File.Delete(Dir + "\\" + GetFileName());
}
}
catch (System.Exception ex)
{
WriteLog("删除日志文件:" + GetFileName() + "失败。失败原因:" + ex.Message);
}
}
}
}