1.引入using System.IO;
2.变量: private bool[] m_inputs = new bool[48];
private bool[] m_alarm = new bool[48];
int alarmno = 0;
private int row = 0;
private string line ="";
private bool isexists = false;
private string rdfilePath = "";
private string fileExtension = "";
private StreamReader reader;
3.读取内容:
for (int i = 0; i < 48; i++)
{
if (m_alarm[i] != m_inputs[i])
{
if (m_inputs[i] == true)
{
alarmno = i + 1;
}
else
{
//alarmno = i + 1;
string endtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
int count = (int)m_RowCount[i];
AlarmGridView.Rows[count].Cells[4].Value = endtime;
AlarmGridView.Rows[count].DefaultCellStyle.BackColor = Color.White;
continue;
}
// 确保只在需要时打开文件
try
{
fileExtension = ".txt";
rdfilePath = AppDomain.CurrentDomain.BaseDirectory + "\\Alarm" + fileExtension;
if (!File.Exists(rdfilePath))
{
MessageBox.Show(rdfilePath + " 不存在", "Alarm", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
reader = new StreamReader(rdfilePath);
while ((line = reader.ReadLine()) != null)
{
string date = DateTime.Now.ToString("yyyy-MM-dd");
string startime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
string Search1 = "Alarm " + alarmno + ":";//空格和冒号为中文模式下的
string Search2 = "Alarm" + alarmno + ":";
if (line.Contains(Search1) || line.Contains(Search2))
{
string starttime = DateTime.Now.ToString();
string[] parts = line.Split(':');
if (parts.Length > 1)
{
line = parts[1].Trim(); // 去除冒号后面的首尾空格
AlarmGridView.Rows[row].Cells[0].Value = date ;
AlarmGridView.Rows[row].Cells[1].Value = alarmno;
AlarmGridView.Rows[row].Cells[2].Value = line;
AlarmGridView.Rows[row].Cells[3].Value = starttime;
AlarmGridView.Rows[row].DefaultCellStyle.BackColor = Color.Red;
// 更新m_alarm数组
m_alarm[i] = m_inputs[i];
isexists = true;
m_RowCount[i] = row;
row++;
break;
}
else
{
Console.WriteLine("No colon found in the " + line);
return;
}
}
}
if (!isexists)
{
MessageBox.Show("Alarm.txt文档不存在Alarm" + "" + alarmno + "警报信息!", "Alarm", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
} catch {
MessageBox.Show("Alarm文档错误", "Alarm", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}