简单的file运用:
实例,创建图下程序,实现读取和写入TXT内容,简单熟悉文件操作的5个主要步骤。
using System.IO; namespace fileform { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void filein_Click(object sender, EventArgs e) { //【1】创建文件流 FileStream fs = new FileStream("D://demo.txt",FileMode.Create); //【2】创建文件写入器 StreamWriter sw = new StreamWriter(fs); //【3】用流的方式写入文件 sw.Write(this.textBox1.Text.Trim()); //【4】关闭文件写入器 sw.Close(); //【5】关闭文件流 fs.Close(); } private void fileout_Click(object sender, EventArgs e) { FileStream fs = new FileStream("D://demo.txt",FileMode.Open); StreamReader sr = new StreamReader(fs); this.textBox1.Text = sr.ReadToEnd(); sr.Close(); fs.Close(); } private void fileinline_Click(object sender, EventArgs e) { FileStream fs = new FileStream("D://demo.txt", FileMode.Append);//在文件尾进行添加 StreamWriter sw = new StreamWriter(fs); sw.WriteLine(this.textBox1.Text.Trim()); sw.Close(); fs.Close(); } } }