建立txt檔案並寫如資料
阿新 • • 發佈:2020-11-12
1. 建立檔案
public static void WriteDataFile(string message, string fileName) { FileStream fs = null; StreamWriter sw = null; string headStr = "測量點\t資料時間\t正向有功總\t正向有功尖\t正向有功峰\t正向有功平\t正向有功谷\t正向無功總\t正向無功尖\t正向無功峰\t正向無功平\t正向無功谷\t反向有功總\t反向無功總\t有功功率總\t有功功率A相\t有功功率B相\t有功功率C相\t無功功率總\t無功功率A相\t無功功率B相\t無功功率C相\t功率因數總\t功率因數A相\t功率因數B相\t功率因數C相\t電壓A\t電壓B\t電壓C\t電流A\t電流B\t電流C"; bool isNew = false; string fileNameD = DateTime.Today.ToString("yyyyMMdd"); string bsFileName = Application.StartupPath + ("/Data/" + fileNameD + "/" + fileName + "Data.txt"); if (File.Exists(bsFileName) == false) { fs = newFileStream(bsFileName, FileMode.Create); fs.Close(); isNew = true; } try { lock (bsFileName) { fs = new FileStream(bsFileName, FileMode.Append, FileAccess.Write); sw= new StreamWriter(fs); if (message == "") { if (isNew == true) { sw.WriteLine(headStr); } } else { sw.WriteLine(message); } } } catch (Exception ee) { Console.Write(ee.ToString()); Log log = Log.Instance(); log.Error("WriteFile" + ee.ToString()); } finally { if (fs != null) { sw.Close(); } if (fs != null) { fs.Close(); } } }
2. 寫入資料或穿件檔案
Common.WriteDemandFile(Protocol.AnalyseDataKeDong(message), dataFileName);