Home  >  Article  >  Backend Development  >  What are the fastest ways to read a text file line by line using C#?

What are the fastest ways to read a text file line by line using C#?

WBOY
WBOYforward
2023-08-26 13:25:052625browse

There are multiple ways to read a text file line by line. These include StreamReader.ReadLine, File.ReadLines, etc. Let's consider the text file that exists within our text file. The local computer has lines like below.

使用 C# 逐行读取文本文件的最快方法有哪些?

Using StreamReader.ReadLine -

C# StreamReader is used to read characters into the specified stream encoding. StreamReader.Read method reads the next character or next group of characters input stream. StreamReader inherits from TextReader and provides the following methods: Read a character, block, line or everything.

Example

using System;
using System.IO;
using System.Text;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         using (var fileStream = File.OpenRead(@"D:\Demo\Demo.txt"))
         using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)){
            String line;
            while ((line = streamReader.ReadLine()) != null){
               Console.WriteLine(line);
            }
         }
         Console.ReadLine();
      }
   }
}

Output

Hi All!!
Hello Everyone!!
How are you?

Use File.ReadLines

File.ReadAllLines() method to open a text file and read all the lines of the file one IEnumerable and then close the file.

Example

using System;
using System.IO;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         var lines = File.ReadLines(@"D:\Demo\Demo.txt");
         foreach (var line in lines){
            Console.WriteLine(line);
         }
         Console.ReadLine();
      }
   }
}

Output

Hi All!!
Hello Everyone!!
How are you?

Using File.ReadAllLines

This is very similar to ReadLines. However, it returns String[] instead of IEnumerable allows us to access rows randomly.

Example

using System;
using System.IO;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         var lines = File.ReadAllLines(@"D:\Demo\Demo.txt");
         for (var i = 0; i < lines.Length; i += 1){
            var line = lines[i];
            Console.WriteLine(line);
         }
         Console.ReadLine();
      }
   }
}

Output

Hi All!!
Hello Everyone!!
How are you?

The above is the detailed content of What are the fastest ways to read a text file line by line using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete