日期:2014-05-17  浏览次数:20906 次

怎样读取txt指定行的数据
一个txt文件,有1000行,怎么快速读取第568行数据?

------解决方案--------------------
两个办法,一个是
从头开始,重复
textreader.readline 568次,
一个是
全部读取进来,根据换行符(\r\n)分割到数组中,取下标567。
------解决方案--------------------
streamreader,一行行读取,计数
------解决方案--------------------
两种方法的代码演示,分别读取eula.txt文件的第100行。(你的电脑上没有这个文件你可以换别的试)。
C# code
string s1 = "";
using (System.IO.TextReader tr = new System.IO.StreamReader("c:\\windows\\system32\\eula.txt"))
{
    s1 = tr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None)[99];
}
Console.WriteLine(s1);

string s2 = "";
using (TextReader tr = new System.IO.StreamReader("c:\\windows\\system32\\eula.txt"))
{
    for (int i = 1; i < 100; i++) tr.ReadLine();
    s2 = tr.ReadLine();
}
Console.WriteLine(s2);

------解决方案--------------------
C# code

private void button1_Click(object sender, EventArgs e)
{
          string[] arr= File.ReadAllLines("d:\\a.txt",Encoding.Default);
          if(arr.Length>568)
          {
                MessageBox.Show(arr[568].ToString());
          }
}

------解决方案--------------------
下面是示例代码

using System;
using System.IO;

class Test 
{
public static void Main() 
{
try 
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
String line;
// Read and display lines from the file until the end of 
// the file is reached.
while ((line = sr.ReadLine()) != null) 
{
Console.WriteLine(line);
}
}
}
catch (Exception e) 
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}