在有些小项目中,要使用到存储LOG信息(纯文本的);此处选用streamwriter示例:
1.库
using System.IO;
2. 源码
namespace HCIUtilsLog
{
class ZGLogMessage
{
System.IO.StreamWriter fs = null;
public void initLog(string folder)
{
string logPath = createFolder(folder);
File.Delete(logPath);
fs = new System.IO.StreamWriter(logPath, true);
fs.AutoFlush = true;
}
public void writeLog(string text)
{
fs.Write(text);
}
public void close()
{
fs.Flush();
fs.Close();
}
private string createFolder(string folder)
{
string subPath = "./capture/" + folder;
if (false == System.IO.Directory.Exists(subPath))
{
System.IO.Directory.CreateDirectory(subPath);
}
return subPath + "/log.txt";
}
}
}
3. 使用
调用initLog创建文件夹,以及获取文件;
private ZGLogMessage zgLog = new ZGLogMessage();
// 此处以串口号为路径名创建路径
zgLog.initLog(cmbDevice.PortName + "_log");
// write string
zgLog.writeLog(text);
// close
zgLog.close();