您的位置:首页 > 其它

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

2013-05-14 20:00 851 查看
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();

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐