码迷,mamicode.com
首页 > Windows程序 > 详细

C#控制台基础 streamreader 中的readline方法读取指定txt文件的所有行

时间:2016-10-11 21:28:43      阅读:435      评论:0      收藏:0      [点我收藏+]

标签:

1、代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace ConsoleApplication4
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             using (StreamReader sReader = new StreamReader(@"1.txt", Encoding.Default))
15             {
16                 string aLine;
17                 //控制while循环是否进行的变量,true打印文本,false跳出循环
18                 bool condition = true;
19 
20                 while (true)
21                 {
22                     
23                     aLine = sReader.ReadLine();
24 
25                     //aline=null 推出 文本读完了,那么控制量condition结合if语句的作用就该是跳出循环                 
26                     //如果文本没有读完,那么condition结合if语句的作用就是输出读到的文本
27                     if (aLine==null)
28                     {
29                         condition = false;
30                     }
31                     
32                     if(condition)
33                     {
34                         Console.WriteLine(aLine);
35                     }
36                     else
37                     {
38                         break;
39                     }
40                 }
41 
42                 
43             }
44             Console.ReadKey();
45         }
46     }
47 }

 

 

2、TXT文件

技术分享

 

3、效果

技术分享

 

 

 

还可以对代码进行改进,用该类自带的成员

1、代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace ConsoleApplication4
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             using (StreamReader sReader = new StreamReader(@"1.txt", Encoding.Default))
15             {
16                 //如果没有到末尾
17                  while(!sReader.EndOfStream)
18                 {
19                     Console.WriteLine(sReader.ReadLine());
20                 }
21             }
22             Console.ReadKey();
23         }
24     }
25 }

 

 

2、效果

技术分享

C#控制台基础 streamreader 中的readline方法读取指定txt文件的所有行

标签:

原文地址:http://www.cnblogs.com/jinlingzi/p/5950462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!