如何在c#中逐行读取文本文件中的文本 [英] how to read text from a text file line by line in c#

查看:74
本文介绍了如何在c#中逐行读取文本文件中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者..

i需要按以下方式逐行读取文本文件=>



读取第一行>在控制台上打印>执行一些功能,如myFunction(line)>在控制台上打印功能给出的>然后读取下一行> .............. ..



没有复杂的答案PLZ。

i知道我是一个菜鸟..别告诉我(-_-)

解决方案

有两种方法:例如,StreamReader类有一个ReadLine方法。

但最简单的方法是一次读取该批次:

  string  [] lines = File.ReadAllLines( @   D:\ Temp \ MyFile.txt); 
foreach string line in 行)
{
Console.WriteLine(line);
string result = DoSomething(line);
Console.WriteLine(result);
}


使用 File.Open [ ^ ]获取流



创建StreamReader [ ^ ]。



使用 ReadLine [ ^ ]方法使用 EndOfS tream属性 [ ^ ]看你是否已经读完整个文件。


使用streamreader有点简单,见下面的代码片段



  int  counter =  0 ; 
string 行;

// 读取文件并逐行显示。
System.IO.StreamReader文件=
new System.IO.StreamReader( < span class =code-string> c:\\test.txt);
while ((line = file.ReadLine())!= null
{
Console.WriteLine(line);
// 在这里调用你的函数
counter ++;
}

file.Close();

// 暂停屏幕。
Console.ReadLine( );


i am a beginner..
i need to read a text file line by line in the following way =>

read the first line>print it on console>carry out some function like myFunction(line)>print on the console what the function gives out>then read the next line>................

no complicated answers plz.
i know im a noob.. dont tell me that (-_-)

解决方案

There are a couple of ways: The StreamReader class has a ReadLine method for example.
But the simplest way is to read the lot at once:

string[] lines = File.ReadAllLines(@"D:\Temp\MyFile.txt");
foreach (string line in lines)
   {
   Console.WriteLine(line);
   string result = DoSomething(line);
   Console.WriteLine(result);
   }


Use File.Open[^] to get a stream

Create an instance of StreamReader[^] for that stream.

Use ReadLine[^] method to read the file line by line, using EndOfStream Property[^] to see if you've read the whole file.


it is bit simple using streamreader, see below snippet

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = 
   new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   //call your function here
   counter++;
}

file.Close();

// Suspend the screen.
Console.ReadLine();


这篇关于如何在c#中逐行读取文本文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆