串口通讯系列二之文件读写操作

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormFile {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {
            DataRead();
        }

        string path = System.Windows.Forms.Application.StartupPath + "\\" + "系统文件" + ".txt";

        private void DataRead() {
            //判断文件是否存在,不存在创建并读取文件内容,显示在控件中
            if(!File.Exists(path)) {
                FileWrite();
                CarryOut();
            } else {
                CarryOut();
            }
        }

        private void FileWrite() {
            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("模式:(调试/运行)");
            sw.WriteLine("调试");
            sw.WriteLine("COM端口:");
            sw.WriteLine("4");
            sw.WriteLine("属性:");
            sw.WriteLine("9600, n, 8, 1");

            sw.Flush();

            sw.Close();
            fs.Close();
        }

        private List<string> FileRead() {
            string line;

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);

            List<string> list = new List<string>();
            while((line = sr.ReadLine()) != null) {
                //排除和删除字符串数组中的空字符串
                if(!string.IsNullOrEmpty(line)) {
                    list.Add(line.ToString());
                }
            }
            
            sr.Close();
            fs.Close();

            return list;
        }

        private void CarryOut() {
            //将文件内所有内容读到textbox1.text中  
            //textBox1.Text = sr.ReadToEnd();

            //实例化一个List集合
            List<string> list = new List<string>();
            //将读取到的数据添加到集合
            list = FileRead();
            //防止误操作
            //获得List中元素数目:List.Count()
            if(list.Count() < 6 || list.Count() > 6) {
                FileWrite();
                CarryOut();
                MessageBox.Show("文件内容缺失,请勿添加或删除文件内容,以重新建立,请修改需要的内容","误操作提示");
            } else {
                // 在textBox1中显示z指定内容
                // 注意!使用 Environment.NewLine 实现换行
                textBox1.AppendText(list[1] + Environment.NewLine);
                textBox1.AppendText(list[3] + Environment.NewLine);
                textBox1.AppendText(list[5] + Environment.NewLine);
            }
            
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值