首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

怎么读取txt指定行的数据

2012-10-17 
怎样读取txt指定行的数据一个txt文件,有1000行,怎么快速读取第568行数据?[解决办法]两个办法,一个是从头开

怎样读取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);
}
}
}

热点排行