C# 文本文件读写问题

来源:互联网 发布:js jq时间段选择控件 编辑:程序博客网 时间:2024/05/22 15:42
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace A42文本文件读写练习
{
    public partial class Form1 : Form
    {
       
        public Form1()
        {
            InitializeComponent();
            buttonll.Click += buttonll_Click;
            buttondq.Click += buttondq_Click;
            buttonbc.Click += buttonbc_Click;
        }
      
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //‪E:\新建文本文档.txt
            string path = @textBox1.Text;
            //string path = @"e:\新建文本文档.txt";
            if (File.Exists(path))
            {
                Console.WriteLine("存在{0}文件", path);
            }
            else
            {
                MessageBox.Show("不存在" + path + "文件");
            }
        }
        //读取按钮
        private void buttondq_Click(object sender, EventArgs e)
        {
            textBox2.Text = null;
           string path = @textBox1.Text;
           try
           {  //using 可以在限定范围结束自动释放资源 不用close
               using (StreamReader sr = new StreamReader(path,System.Text.Encoding.Default))
               {
                   string line;
                   while ((line = sr.ReadLine()) != null)
                   {
                       textBox2.Text += line+"\r\n"; //\r回车符 \n换行符                    
                   }
               }
           }
           catch(Exception e1)
           {
               MessageBox.Show(e1.Message);
           }
        }
        //浏览按钮
        private void buttonll_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            textBox1.Text = this.openFileDialog1.FileName;       
        }
        //保存按钮
        void buttonbc_Click(object sender, EventArgs e)
        {
            string path = @textBox1.Text;
            try
            {
                using (StreamWriter sw = new StreamWriter(path,false, System.Text.Encoding.Default))
                {
                    sw.Write(textBox2.Text);
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
    }
}
0 0
原创粉丝点击