当前位置:   article > 正文

C#使用StreamReader类和StreamWriter类读写文本文件_stream阅读word

stream阅读word

StreamReader类和StreamWriter类可以实现读写文本文件,这两个类都在命名空间System.IO下。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormStream
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnWriter_Click(object sender, EventArgs e)
        {
            using (StreamWriter streamWriter = new StreamWriter("test.txt"))
            {
                for (int i = 1; i <= 10; i++)
                {
                    streamWriter.WriteLine(i + ":" + DateTime.Now.ToString() + " \r\n");
                }
            }
            MessageBox.Show("文件写入成功!");
        }

        private void btnReader_Click(object sender, EventArgs e)
        {
            try
            {
                if (!File.Exists("test.txt"))
                {
                    MessageBox.Show("test.txt文件不存在");
                }
                using (StreamReader streamReader = new StreamReader("test.txt"))
                {
                    string line;
                    StringBuilder stringBuilder = new StringBuilder();
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        stringBuilder.Append(line);
                    }
                    MessageBox.Show(stringBuilder.ToString());
                }
            } catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

1

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/367387
推荐阅读
相关标签
  

闽ICP备14008679号