C#--读写文件

来源:互联网 发布:vb和c语言哪个难 编辑:程序博客网 时间:2024/05/22 17: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 WindowsFormsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {        }        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();        }    }}


0 0