创建一个如下的窗体,并在窗体上放置saveFileDialog、openFileDialog两个控件。

来源:互联网 发布:json setid用法 编辑:程序博客网 时间:2024/04/26 17:21
 
//<p align="left">创建一个如下的窗体,并在窗体上放置saveFileDialog、openFileDialog两个控件。实现功能:1)程序运行时,在文本框(注意文本框多行、带垂直滚动条)中输入汉字、字符等,单击保存按钮,即可将文本框中内容保存到一个文件(用到:P232页 8.3.2文本文件读写知识);2)单击打开按钮,可选择文本文件,并读取文件中内容,显示在文本框中。</p>
 
 
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;namespace WindowsFormsApplication1{    public partial class Form2 : Form    {        public Form2()        {                       InitializeComponent();            button2.Text = "打开文本文件";        }        private void 保存文本文件_Click(object sender, EventArgs e)        {            this.saveFileDialog1.Filter = "*.txt|*.txt";            this.saveFileDialog1.ShowDialog();            string file = this.saveFileDialog1.FileName;            if (string.IsNullOrEmpty(file)) return;            //以下为写字符到文本文件,需要添加System.IO引用            //创建一个文件流            FileStream fs = new FileStream(file, FileMode.OpenOrCreate,                FileAccess.Write);            //创建一个StreamWriter对象            StreamWriter sw = new StreamWriter(fs);            sw.Write(this.textBox1.Text);            //释放StreamWriter对象,文件流对象            sw.Dispose();            fs.Dispose();        }        private void button2_Click(object sender, EventArgs e)        {            this.openFileDialog1.Filter = "*.txt|*.txt";            this.openFileDialog1.ShowDialog();            string file = this.openFileDialog1.FileName;            if (string.IsNullOrEmpty(file)) return;            //以下为写字符到文本文件,需要添加System.IO引用            //创建一个文件流            FileStream fs = new FileStream(file, FileMode.Open,                FileAccess.Read);            //创建一个StreamWriter对象            StreamReader sr = new StreamReader(fs);            this.textBox1.Text = sr.ReadToEnd();            //释放StreamWriter对象,文件流对象            sr.Dispose();            fs.Dispose();                    }        private void textBox1_TextChanged(object sender, EventArgs e)        {        }    }}

0 0
原创粉丝点击