Windows窗体编程基础学习:文件读写

1.[读取]按钮
  判断某txt文件是否存在 不存在则新建
  读取文件中的内容
2.[写入]按钮
  将用户修改后的内容 存入该txt文件

===============================
1.新建专案 及 加入 新建项目 Windows窗体(如txtFileReadWrite)
  并设定应用程序的主入口点
  Application.Run(new txtFileReadWrite());

2.该窗体加入两个按钮(读取和写入) 及 一个文本框

3.代码部分加入引用
  using System.IO;

4.[读取] 按钮 事件 代码
private void btn_txtFileRead_Click(object sender, EventArgs e)
{
    try
    {
        string strDirPath = "E:\\WinFormStudy\\";
        string strFilePath = "E:\\WinFormStudy\\myText.txt";               
        if (File.Exists(strFilePath))
        {
            //如果存在 则读取其中的文本内容
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string strLineText = "";
                string strAllText = "";
                while ((strLineText = sr.ReadLine()) != null)
                {
                    strAllText += strLineText;
                }
                this.textBox1.Text = strAllText;
            }
        }
        else//如果不存在 则创建
        {
            if (!Directory.Exists(strDirPath))
            {
                Directory.CreateDirectory(strDirPath);
            }
            File.Create(strFilePath);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

5.[写入] 按钮 事件 代码
private void btn_txtFileWrite_Click(object sender, EventArgs e)
{
    string strFilePath = "E:\\WinFormStudy\\myText.txt";
    if (File.Exists(strFilePath))
    {
        using (StreamWriter sw = new StreamWriter(strFilePath))
        {
            // 增加一些文件描述
            sw.Write("这是新修改后的文件");                   
            sw.Write("修改的时间为: ");
            sw.WriteLine(DateTime.Now);
            sw.WriteLine("-------------------");
            sw.WriteLine(this.textBox1.Text);                   
        }
    }
    else
    {
        MessageBox.Show("文件不存在 请先创建");
    }
}

原文地址:https://www.cnblogs.com/freeliver54/p/694087.html