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("文件不存在 请先创建");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值