在有些小項目中,要使用到存儲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();