C#streamreader指定读取第几行

本文介绍如何使用C#从文本文件中读取特定行并显示在Winform应用程序的TextBox控件中。提供了两种方法:一种使用StreamReader,另一种直接使用File.ReadAllLines。

C#streamreader指定读取第几行

winform程序,有textbox1和textbox2,如何通过streamreader将第一行数据的值传给textbox1,将第二行的值传给textbox2?
打到凹凸曼  |  浏览 5322 次  |举报
我有更好的答案
 
推荐于2017-11-26 19:45:37 最佳答案
 
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
using  System.IO
 
public  partial Form1 : Form
{
     List< string > lines;
     public  Form1()
      {
             InitializeComponent();
             //存放所有行的集合
             lines =  new  List< string >();
      }
      
      private  void  Form1_Load( object  sender, System.EventArgs e)
      {
             FileStream fs =  new  FileStream( "TextFile1.txt" , FileMode.Open);
             StreamReader rd =  new  StreamReader(fs);
             string  s;
             //读入文件所有行,存放到List<string>集合中
             while ( (s= rd.ReadLine() )!=  null )
             {
                 lines.Add(s);
             }         
             rd.Close();
             fs.Close();
             //第一行在textBox1中显示
             if (lines.Count > 0 )
             {
                 textBox1.Text = lines[0];
             }
             //第二行在textBox2中显示
             if (lines.Count > 1)
             {
                 textBox2.Text = lines[1];
             }
      }
}

还有更简单的方法,不使用StreamReader。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public  partial Form1 : Form
{
     string [] lines;
     public  Form1()
      {
             InitializeComponent();
      }
      
      private  void  Form1_Load( object  sender, System.EventArgs e)
      {
             lines = File.ReadAllLines( "TextFile1.txt" );
             //第一行在textBox1中显示
             if (lines.Length > 0 )
             {
                 textBox1.Text = lines[0];
             }
             //第二行在textBox2中显示
             if (lines.Length > 1)
             {
                 textBox2.Text = lines[1];
             }
      }
}
 
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值