我正在动态编写(.csv)文件中的三个变量,我想在这三个变量中添加Headers。我的代码是......
private void timer2_Tick(object sender, EventArgs e)
{
string dt = DateTime.Now.ToString("hh.mm.ss.ffffff");
StreamWriter writer = File.AppendText(NameYourFile.Text + DateTime.Today.ToString("MM_dd_yyyy") + ".csv");
string var =(dt) + ',' + adsClient.ReadAny(hActVel, typeof(double)).ToString() + ',' + adsClient.ReadAny(hSActVel, typeof(double)).ToString();
string[] lines =
foreach (string line in lines)
{
if(line == lines[0])
{
writer.WriteLine( string.Format("{0},{1},{2}", "Time", "Big Motor Actual Velocity", "Small Motor Actual Velocity"));
}
}
writer.WriteLine(var);
writer.Dispose();
}
谢谢
答案 0 :(得分:0)
public class adsClientEntry
{
public DateTime EntryTime;
public double BigMotorVelocity;
public double SmallMotorVelocity;
}
private void Form1_Load(object sender, System.EventArgs e)
{
CreateFile();
}
public void CreateFile()
{
string path = YourFileName.Text + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".csv";
if (!System.IO.File.Exists(path))
{
// Create file if no Exists
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(string.Format("{0},{1},{2}", "Time", "Big Motor Actual Velocity", "Small Motor Actual Velocity"));
}
}
}
private void AppendLog(adsClientEntry thisEntry)
{
string path = YourFileName.Text + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".csv";
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(string.Format(
"{0},{1},{2}",
thisEntry.EntryTime.ToString("hh.mm.ss.ffffff"),
thisEntry.BigMotorVelocity.ToString(),
thisEntry.SmallMotorVelocity.ToString()
));
}
}
private void timer2_Tick(object sender, EventArgs e)
{
adsClientEntry thisEntry = new adsClientEntry();
thisEntry.EntryTime = DateTime.Now();
thisEntry.BigMotorVelocity = adsClient.ReadAny(hActVel, typeof(double));
thisEntry.SmallMotorVelocity = adsClient.ReadAny(hSActVel, typeof(double));
AppendLog(thisEntry);
}