实现代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 读写txt之2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
label3.Visible= false;
}
string FilePath;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog SelectTxtDialog = new OpenFileDialog();
if (SelectTxtDialog.ShowDialog(this) == DialogResult.OK)
{
FilePath = Path.GetFullPath(SelectTxtDialog.FileName);
textBox1.Text = FilePath;
}
}
private void Readdata()
{
bool getTime = false;
StreamReader strFile = new StreamReader(FilePath);
string line;
DateTime t1 = DateTime.MinValue;
string date1 = "", date2;
line = strFile.ReadLine();
date1 = check(line);
t1 = GetDateTime(date1);
while (!strFile.EndOfStream)
{
if (getTime == true)
{
getTime = false;
line = strFile.ReadLine();
date1 = check(line);
t1 = GetDateTime(date1);
}
line = strFile.ReadLine();
if (line.Contains("&BE01"))//以报文检验码为结束点进行判断
{
date2 = check(line);
DateTime t2 = GetDateTime(date2);
System.TimeSpan t3 = t2 - t1;
SaveFile(t3.ToString(), date1, date2);
}
if (line == null || line == "")//判断当前行是否为空
{
getTime = true;
}
}
strFile.Close();
textBox2.Text = newTxtPath;
label3.Text = "分析完成!";
label3.Visible = true;
}
public DateTime GetDateTime(string dateTime)
{
string[] strArr = dateTime.Split(new char[] { '-', ' ', ':', ',', ':' });
DateTime dt = new DateTime(int.Parse(strArr[0]),
int.Parse(strArr[1]),
int.Parse(strArr[2]),
int.Parse(strArr[3]),
int.Parse(strArr[4]),
int.Parse(strArr[5]),
int.Parse(strArr[6]));
return dt;
}
public string check(string s)
{
Regex reg2 = new Regex(@"(20[012]\d-[01]\d-[0123]\d\s\d\d:\d\d:\d\d:\d\d\d)");
MatchCollection matches = reg2.Matches(s);
string line = "";
if (matches.Count >= 1)
{
line = matches[0].Value;
}
return line;
}
string newTxtPath;
public void SaveFile(string ss, string d1, string d2)
{
string mpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "时间差保存");//保存文件路径
if (!Directory.Exists(mpath))
Directory.CreateDirectory(mpath);
string fileName = @"\" + DateTime.Now.ToString("yyyyMMddHHmm") + "时间差保存.txt";
newTxtPath = mpath + fileName;
StreamWriter sw2 = new StreamWriter(newTxtPath, true, Encoding.UTF8);//实例化StreamWriter;//true表示允许追加
sw2.WriteLine(ss + "\t" + d1 + "\t" + d2);
sw2.Flush();
sw2.Dispose();
sw2.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Readdata();
}
}
}