我必须创建winform应用程序,它在文本文件中写入开始时间和停止时间,以便文本文件中的数据可用于在图形中显示。现在我已设法让计时器在文本文件中写入开始和停止时间,但计时器写入完整的持续时间
即;
8/13/2014 8:33:57 PM
8/13/2014 8:33:57 PM
8/13/2014 8:33:58 PM
8/13/2014 8:33:58 PM
8/13/2014 8:33:59 PM
8/13/2014 8:33:59 PM
8/13/2014 8:34:00 PM
但我希望计时器只写开始时间和结束时间。
using System;
using System.Windows.Forms;
using System.IO;
using System.Text;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
FileStream fs = new FileStream(@"D:\Hello.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
//FileStream fs = new FileStream(@"E:\log{0:yyyy-MM-dd HH:mm:ss}.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite),sb.ToString());
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now.Hour);
lbTimer.Items.Add(DateTime.Now.Hour+"Hours");
lbTimer1.Items.Add(DateTime.Now.Minute+"M");
lbTimer2.Items.Add(DateTime.Now.Second+"s");
fs.Flush();
sw.Close();
fs.Close();
}
}
}
答案 0 :(得分:1)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
File.AppendAllText("D:\\Hello.txt", DateTime.Now.ToString());
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
File.AppendAllText("D:\\Hello.txt", DateTime.Now.ToString());
}
}
答案 1 :(得分:0)
这可以是一个选项,收集所有日期并写入文件一次:
string path = @"yourpathhere";
List<string> dates = new List<string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dates.Add(DateTime.Now.ToString());
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
dates.Add(DateTime.Now.ToString());
File.WriteAllText(path, dates.Aggregate((d1, d2) => d1 + "\r\n" + d2));
}
答案 2 :(得分:0)
你可以试试这个......
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (System.IO.StreamWriter streamWriter = new StreamWriter("Report.txt", false))
{
streamWriter.WriteLine(string.Format("Start Time : {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
}
}
private void Form_Closed(object sender, EventArgs e)
{
using (System.IO.StreamWriter streamWriter = new StreamWriter("Report.txt", true))
{
streamWriter.WriteLine(string.Format("End Time : {0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
}
}
}