1.变量:
string data = "";
string alarmno = "";
string line = "";
string startime = "";
string endtime = "";
string fileExtension = ".txt";
string wtfilePath = AppDomain.CurrentDomain.BaseDirectory + "\\AlarmInfor" + fileExtension;
2.写值:
string headerText = "日期" + " " + "警报编号" + " " + "警报文本" + " " + "发生时间" + " " + "确认时间";
// 检查文件是否存在,如果不存在则创建
if (!File.Exists(wtfilePath))
{
// 使用File.Create创建文件
using (FileStream fs = File.Create(wtfilePath))
{
// 创建空文件
}
}
try
{
// 使用StreamWriter写入头部文本
// 这里使用FileMode.Create会覆盖文件内容,如果要追加请使用FileMode.Append
using (StreamWriter writer = new StreamWriter(wtfilePath, false)) // false 表示覆盖模式
{
writer.WriteLine(headerText);
writer.WriteLine("-------------------------------------------------------------------------------------");
}
Console.WriteLine("头部文本写入成功。");
}
catch (Exception ex)
{
// 处理可能发生的异常
Console.WriteLine("写入头部文本失败: " + ex.Message);
}
for (int i = 0; i < 48; i++)
{
//获取表格上的值
data = AlarmGridView.Rows[i].Cells[0].Value?.ToString() ?? "";
alarmno =AlarmGridView.Rows[i].Cells[1].Value?.ToString() ?? "";
line = AlarmGridView.Rows[i].Cells[2].Value?.ToString() ?? "";
startime = AlarmGridView.Rows[i].Cells[3].Value?.ToString() ?? "";
endtime = AlarmGridView.Rows[i].Cells[4].Value?.ToString() ?? "";
string textToWrite = data + " " + alarmno + " " + line + " " + startime + " " + endtime;
//写入txt档中
try
{
// 使用StreamWriter写入头部文本
// 这里使用FileMode.Create会覆盖文件内容,如果要追加请使用FileMode.Append
using (StreamWriter writer = new StreamWriter(wtfilePath, true)) // false 表示覆盖模式
{
writer.WriteLine(textToWrite);
}
Console.WriteLine("文本写入成功。");
}
catch (Exception ex)
{
// 处理可能发生的异常
Console.WriteLine("写入文本失败: " + ex.Message);
}
}