C#文件写入及读取
功能
- 功能
- 程序
- 实现效果
- 后续
左边的分组框用于输入学生信息(包括学号、姓名、性别、年龄和分数),用户单击“添加”命令按钮时将当前学生信息添加到指定的文本文件中;右边的分组框用于显示所有存储在指定文件中的学生记录,执行界面如下图:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace 文件操作
{
public partial class Form1 : Form
{
string path = "D:\\master.txt";//文件名
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i;
string mystr = "学号\t\t姓名\t性别\t年龄\t分数\r\n";
FileStream fs = File.OpenRead(path);
StreamReader st = new StreamReader(fs, Encoding.GetEncoding("UTF-8"));//必须更改为UTF-8类型,不然会乱码
//用指定的字符编码为指定的流初始化一个StreamReader类新实例
//指定打开文件
fs.Seek(0, SeekOrigin.Begin);//将文件流指针定位在开始位置
while (st.Peek() > -1)
{
mystr = mystr + st.ReadLine() ;
mystr = mystr + "\r\n";
}
st.Close();
fs.Close();
textBox1.Text = mystr;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string str;
if(!File.Exists(path))//如果不存在,则创建
{
StreamWriter sw = File.CreateText(path);
sw.Close();
}
if(textBox2.Text!="")
{
str = textBox2.Text + "\t" + textBox3.Text + "\t" + textBox4.Text + "\t" + textBox5.Text + "\t" + textBox6.Text;
StreamWriter sb = new StreamWriter(path,true,Encoding.UTF8);
sb.WriteLine(str);
sb.Close();
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
button2.Enabled = false;
textBox2.Focus();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
button2.Enabled = true;
}
}
}
实现效果
在左边可以进行学生信息的录入,在右边可以进行学生信息的读取。
如果想了解更多物联网、智能家居项目知识,可以关注我的程序设计专栏。 或者关注公众号。
编写不易,感谢支持。