c# 对txt文件的读取与写入

C# txt文件分析 读取与写入

c#中对txt文件的读取写入在工作中用到的很多,今天写一个之前工作中用到的小demo~
案例场景要求:
txt文件中为很多条标记时间戳的报文,需要计算出每条报文从开始接收到结束用了多长时间
案例执行:
如txt文件中只有少量的报文可直接手动计算,但当txt中存在大量的数据时写一个小程序让其自动执行更高效。以下案例中,实现过程:点击加载按钮将所需要执行的文件夹路径加载进来,然后点击文件分析,即可自动执行分析txt文件,并将所有计算出来的时间差重新保存写入一个新的文件。
其中因在txt文件中存在空白行,所以代码中对空白行进行了判断。
注:本文中用到的测试文件为串口助手保存的报文文件。
运行截图:
运行图一
运行图二
测试文件:
测试文件图
新生成的时间差文件:
在这里插入图片描述
实现过程代码:

    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 btnAnalyse_Click(object sender, EventArgs e)
        {
            Readdata();
        }
    }

可自行新建一个txt文件 将报文拷入文件 并复制粘贴多个此报文 即可测试
报文如下:
【2021-12-29 09:20:51:192】##0457ST=22;CN=2011;PW=1111;MN=21030016;CP=&&DataTime=20211229092032;pmACT-Rtd=8.3,pmACT-Flag=N;
【2021-12-29 09:20:51:242】pmSTD-Rtd=8.7,pmSTD-Flag=N;temperature-Rtd=16.1,temperature-Flag=N;humidity-Rtd=14.0,humidity-Fl
【2021-12-29 09:20:51:292】ag=N;atmosphere-Rtd=1021,atmosphere-Flag=N;flow-Rtd=16.63,flow-Flag=N;pttemp-Rtd=36.6,pttemp-Fla
【2021-12-29 09:20:51:342】g=N;cygtemp-Rtd=39.3,cygtemp-Flag=N;jxtemp-Rtd=18.8,jxtemp-Flag=N;yqtemp-Rtd=25.1,yqtemp-Flag=N;
【2021-12-29 09:20:51:392】inter-pressure-Rtd=859,inter-pressure-Flag=N;iampleRH-Rtd=2.2,iampleRH-Flag=N&&BE01

【2021-12-29 09:20:59:882】##0457ST=22;CN=2011;PW=1111;MN=21030016;CP=&&DataTime=20211229092041;pmACT-Rtd=8.3,pmACT-Flag=N;
【2021-12-29 09:20:59:882】pmSTD-Rt
【2021-12-29 09:20:59:932】d=8.7,pmSTD-Flag=N;temperature-Rtd=16.1,temperature-Flag=N;humidity-Rtd=14.0,humidity-Fl
【2021-12-29 09:20:59:932】ag=N;atm
【2021-12-29 09:20:59:982】osphere-Rtd=1021,atmosphere-Flag=N;flow-Rtd=16.65,flow-Flag=N;pttemp-Rtd=37.0,pttemp-Fla
【2021-12-29 09:20:59:982】g=N;cygt
【2021-12-29 09:21:00:032】emp-Rtd=39.2,cygtemp-Flag=N;jxtemp-Rtd=18.8,jxtemp-Flag=N;yqtemp-Rtd=25.1,yqtemp-Flag=N;
【2021-12-29 09:21:00:032】inter-pr
【2021-12-29 09:21:00:082】essure-Rtd=859,inter-pressure-Flag=N;iampleRH-Rtd=2.3,iampleRH-Flag=N&&BE01

【2021-12-29 09:21:08:569】##0457ST=22;CN=2011;PW=1111;MN=21030016;CP=&&DataTime=20211229092049;pmACT-Rtd=8.3,pmACT-Flag=N;
【2021-12-29 09:21:08:619】pmSTD-Rtd=8.7,pmSTD-Flag=N;temperature-Rtd=16.1,temperature-Flag=N;humidity-Rtd=14.0,humidity-Fl
【2021-12-29 09:21:08:669】ag=N;atmosphere-Rtd=1021,atmosphere-Flag=N;flow-Rtd=16.65,flow-Flag=N;pttemp-Rtd=36.6,pttemp-Fla
【2021-12-29 09:21:08:719】g=N;cygtemp-Rtd=39.4,cygtemp-Flag=N;jxtemp-Rtd=18.9,jxtemp-Flag=N;yqtemp-Rtd=25.0,yqtemp-Flag=N;
【2021-12-29 09:21:08:769】inter-pressure-Rtd=859,inter-pressure-Flag=N;iampleRH-Rtd=2.3,iampleRH-Flag=N&&BE01

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值