Fileatream表示文件流,它能够打开和关闭文件,并对文件进行单字节的读写操作。 StreamReader和StreamWriter以文本方式对流进行读写操作。建立一个文本文件,分别使用上面两种方

来源:互联网 发布:动态演示软件 编辑:程序博客网 时间:2024/06/06 23:21
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 WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //读文件
            if (string.IsNullOrEmpty(this.textBox1.Text.Trim()))
            {
                MessageBox.Show("必须输入待读文件路径及文件名");
                return;
            }
            FileStream fs =
                new FileStream(this.textBox1.Text,
                    FileMode.OpenOrCreate, FileAccess.Read);
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            this.textBox2.Text = Encoding.UTF8.GetString(bytes);
            fs.Dispose();


        }


        private void button2_Click(object sender, EventArgs e)
        {
            //写文件
            if (string.IsNullOrEmpty(this.textBox1.Text.Trim()))
            {
                MessageBox.Show("必须输入待写文件路径及文件名");
                return;
            }
            FileStream fs =
                new FileStream(this.textBox1.Text,
                    FileMode.Create, FileAccess.Write);
            byte[] bytes = Encoding.UTF8.GetBytes(this.textBox2.Text.Trim());
            fs.Write(bytes, 0, bytes.Length);
            fs.Dispose();


        }
    }
}