c#StreamWriter,StreamReader类(主要用于文本文件访问)

1、为什么要使用StreamReader或者StreamWriter

如果对文本文件需要读取一部分显示一部分则使用FileStream会有问题,因为可能FileStream会在读取的时候把一个汉字的字节数给分开。所以造成显示的时候无法正确显示字符串。所以对于读取大文本文件一般使用StreamReader类。对于大文本文件写入一般用StreamWriter类。

2、StreamWriter

            //1.创建一个StreamWriter
            using (StreamWriter sw = new StreamWriter("test.txt", false, Encoding.UTF8))
            {
                //2.执行读写
                for (int i = 0; i < 1000; i++)
                {
                    sw.WriteLine(i + "======" + System.DateTime.Now.ToString());
                }
            }
            Console.WriteLine("ok");
            Console.ReadKey();

3、StreamReader

            #region StreamReader使用
            //1.创建StreamReader 对象
            using (StreamReader reader = new StreamReader("英汉词典TXT格式.txt", Encoding.Default))
            {
                #region 1
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    Console.WriteLine(line);
                }
                #endregion
                #region 2
                int count = 0;
                while (reader.ReadLine() != null)
                {
                    count++;
                    Console.WriteLine(reader.ReadLine());
                }
                Console.WriteLine(count );
                File.ReadAllLines(
                #endregion
                #region 2
                //2.循环读取每一行数据。
                string line = null;
                int count = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    count++;
                    Console.WriteLine(line);
                }
                //Console.WriteLine(count);

                #endregion
            }
            Console.WriteLine("ok");
            Console.ReadKey();
            #endregion

  

转载于:https://www.cnblogs.com/crhdyl/p/4994174.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值