C#streamreader指定读取第几行

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];
             }
      }
}
 

猜你喜欢

转载自hypercube.iteye.com/blog/2404116
今日推荐