我的英文名叫Ahsun

用代码书写心情

导航

txt做log,一条一条的写数据,监听设备做log

 这个是一个向txt文件中一条一条的写数据
以前在公司写到这样的一个小功能,可能大家也会有需要,特此分享给有需要的朋友们。

//构造函数中定义好传入的参数,这样就不会每写一条数据就一个txt文件了。
public NavfixForm()
{
InitializeComponent();
string dateTime = DateTime.Now.ToString("yyyyMMddhhmmss");
string fileName = "Navfix" + dateTime + ".txt";
filePath
= EnvironmentUtil.CurrentPath + fileName;
}

// 在xx函数中调用WriteLogAutomatic方法
string fileContent = DateTime.Now.ToString("hh:mm:ss") + navfix.NativeString.ToString();
WriteLogAutomatic(filePath,fileContent);

/// <summary>
/// Write the log Automatic
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileContent"></param>
/// <returns></returns>
private bool WriteLogAutomatic(string filePath, string fileContent)
{
if (cbxAutoWriteLog.Checked)
{
try
{
System.IO.FileStream oFileStream;
if (!string.IsNullOrEmpty(this.txtFixLog.Text))
{

oFileStream
= new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
}
else
{
oFileStream
= new System.IO.FileStream(filePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
}
System.IO.StreamWriter oStreamWriter
= new System.IO.StreamWriter(oFileStream, System.Text.Encoding.Default);
oStreamWriter.Write(fileContent);
oStreamWriter.WriteLine();
oStreamWriter.Close();
oFileStream.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
return true;
}

posted on 2011-02-15 14:44  Ahsun  阅读(286)  评论(0)    收藏  举报