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);
}
}
}
}
串口通讯系列二之文件读写操作
最新推荐文章于 2023-11-13 16:28:43 发布