zoukankan      html  css  js  c++  java
  • 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("文件不存在 请先创建");
        }
    }

  • 相关阅读:
    14、迭代器协议、生成器、装饰器
    13、文件处理
    12、内置函数
    11、函数(def)
    10、基本数据类型(set)
    9、循环语句
    8、基本数据类型(dict)
    7、基本数据类型(tuple)
    6、基本数据类型(list)
    5、基本数据类型(str)
  • 原文地址:https://www.cnblogs.com/freeliver54/p/694087.html
Copyright © 2011-2022 走看看