C# IO读取指定行数

1.利用File类,返回带有每一行的string[]数组,强烈推荐使用

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

 

 

2. C#2.0前,FileStream,不推荐使用

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

 

posted @ 2015-04-24 11:08  Cvjar  阅读(961)  评论(0编辑  收藏  举报