读写文本文件

  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7// 添加新的命名空间。
  8using System.IO;
  9using System.Text;
 10
 11namespace TextFile
 12{
 13    /// <summary>
 14    /// 处理文本文件。
 15    /// </summary>

 16    public class Form1 : System.Windows.Forms.Form
 17    {
 18        private System.Windows.Forms.Button button1;
 19        private System.Windows.Forms.Button button2;
 20        private System.Windows.Forms.RichTextBox richTextBox1;
 21        private System.Windows.Forms.TextBox textBox1;
 22        private System.Windows.Forms.Label label1;
 23        private System.Windows.Forms.OpenFileDialog openFileDialog1;
 24        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
 25        /// <summary>
 26        /// 必需的设计器变量。
 27        /// </summary>

 28        private System.ComponentModel.Container components = null;
 29
 30        public Form1()
 31        {
 32            //
 33            // Windows 窗体设计器支持所必需的
 34            //
 35            InitializeComponent();
 36
 37            //
 38            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 39            //
 40        }

 41
 42        /// <summary>
 43        /// 清理所有正在使用的资源。
 44        /// </summary>

 45        protected override void Dispose( bool disposing )
 46        {
 47            if( disposing )
 48            {
 49                if (components != null)
 50                {
 51                    components.Dispose();
 52                }

 53            }

 54            base.Dispose( disposing );
 55        }

 56
 57        Windows Form Designer generated code
140
141        /// <summary>
142        /// 应用程序的主入口点。
143        /// </summary>

144        [STAThread]
145        static void Main()
146        {
147            Application.Run(new Form1());
148        }

149        // 定义私有变量
150        // 读文件
151        public TextWriter w;
152        // 写文件
153        public TextReader r;
154        // 读文本文件
155        private void button1_Click(object sender, System.EventArgs e)
156        {
157            if(openFileDialog1.ShowDialog() == DialogResult.OK)
158            {
159                textBox1.Text = openFileDialog1.FileName;
160                r = new StreamReader(openFileDialog1.FileName);
161                richTextBox1.Text = r.ReadToEnd();
162                r.Close();
163            }

164        }

165        // 写文本文件
166        private void button2_Click(object sender, System.EventArgs e)
167        {
168            if(saveFileDialog1.ShowDialog() == DialogResult.OK)
169            {
170                textBox1.Text = saveFileDialog1.FileName;
171                w = new StreamWriter(saveFileDialog1.FileName);
172                w.Write(richTextBox1.Text);
173                w.Flush();
174                w.Close();
175            }

176        }

177    }

178}

179
posted on 2007-08-21 16:30  Gofficer  阅读(454)  评论(0)    收藏  举报