使用c# 往.TXT档中写值

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);
                }


            }

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值