StreamReader和StreamWriter類的基本操作

iamzxf發表於2015-06-07


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 streamRWFormDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "文字檔案(*.txt)|*.txt";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Text = "";
                string path = openFileDialog1.FileName;
                StreamReader sr = new StreamReader(path, Encoding.Default);
                richTextBox1.Text = sr.ReadToEnd();
                sr.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (richTextBox1.Text == "")
                MessageBox.Show("檔案內容不能為空!");
            else
            {
                saveFileDialog1.Filter = "文字檔案(*.txt)|*.txt";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string path = saveFileDialog1.FileName;
                    StreamWriter sw = new StreamWriter(path);
                    sw.Write(richTextBox1.Text);
                    sw.Close();
                }
            }
        }
    }
}



相關文章