c#读写文件遇到问题,请高手指引

richerg85 2012-06-01 09:45:00
c#通过写文件的形式记log,当我写log的同时,我用记事本或者UE打开写的文件,会遇到log不再写,程序好像停在写log的位置。

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);
}
}
}
}

我想用单例的模式引用这个log类,引用代码如下
这个引用是在我想记log的类中。
public RecordLog log = RecordLog.GetInstance();

写log:
log.WriteLog("事件未注册");

出现上述描述的问题,请问如何解决,谢谢!
...全文
110 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
richerg85 2012-06-01
  • 打赏
  • 举报
回复
c#有系统的log?我只是想写自己记日志的log
风之影子 2012-06-01
  • 打赏
  • 举报
回复
藐视楼主用的不是系统的EventLog控件

风之影子 2012-06-01
  • 打赏
  • 举报
回复
CreateEventSource();

事件源需要注册

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧