Home  >  Article  >  Backend Development  >  C# program reads file contents line by line

C# program reads file contents line by line

WBOY
WBOYforward
2023-08-28 12:41:081213browse

C# 程序逐行读取文件内容

Introduction

Here, we will learn to write a C# program to read the file content line by line. There are several ways to do this. We will discuss them one by one.

File handling is done in C#. Most of the time, files are used to store data. In layman's terms, file processing or file management are various processes such as creating files, reading files, writing files, appending files, etc. Reading and writing files are two of the most common operations in file processing.

1. Using the File.ReadLines() method

The first way to read the contents of a file line by line is to use the File.ReadLines() method. This method accepts character encoding as an optional parameter.

Well, this process may throw some exceptions, such as IO exceptions. This error is thrown if an I/O error occurs; another error, FileNotFoundException, is thrown if the file trying to open cannot be found.

This process also has a drawback, as this technique is quite inefficient when you are dealing with large files. This returns an Enumerable through which we can start enumeration before returning the entire collection.

algorithm

The algorithm below will give the step-by-step process of reading the contents of a file line by line using the File.ReadLines() method.

The algorithms discussed below will guide us in creating the program.

Step 1 Create a string to store the name of the file path, remember this is an absolute path.

Step 2 When reading the file line by line, use IEumerable to obtain the final result.

Step 3 Get the newline string defined for the environment by using Environment.Newline. Then the program ends.

Example

The following is the code for this process -

using System;
using System.Collections.Generic;
using System.IO;

public class Example {
   public static void Main() {
      string fileloc = @"D:\ttpt\locew.txt";

      IEnumerable<string> lines = File.ReadLines(fileloc);
      Console.WriteLine(String.Join(Environment.NewLine, lines));
   }
} 

Output

This is a file.
Hello from tutorials point.

First you need to create a string type variable that contains the address of the file location. After that, read the file line by line in the program.

2. Using the File.ReadAllLines() method

Another way to read the contents of a file line by line is to use the File.ReadAllLines() method. For big data files, we should not use ReadAllLines as ReadAllLines, unlike ReadLines which returns an Enumerable, ReadAllLines gives a string array containing all the lines of the file and we have to wait for the entire string array to be returned before we can access the array.

This method accepts character encoding as an optional parameter, similar to what ReadLines does. Then this process may throw some exceptions, such as IO Exception. This error is thrown if an I/O error occurs; another error, FileNotFoundException, is thrown if the file trying to open cannot be found.

algorithm

The algorithm below will give the step-by-step process of reading the file content line by line using the File.ReadAllLines() method.

The algorithms discussed below guide us in creating the program.

Step 1 Create a string to store the name of the file path, remember this is an absolute path.

Step 2 Next, the program uses ReadAllLines to open a text file, read all its lines, and then terminate it.

p>

Step 3 Get the newline character string defined for the environment by using Environment.Newline. Then the program ends.

Example

The following is the code for this process -

using System;
using System.IO;

public class Example {
   public static void Main() {
      string fileloc = @"D:\ttpt\locew.txt";
      string[] lines = File.ReadAllLines(fileloc);
      Console.WriteLine(String.Join(Environment.NewLine, lines));
   }
}

Output

This is a file.
Hello from tutorials point.

First you need to create a string type variable that contains the address of the file location. After that, read the file line by line in the program. Here, the difference is that the lines are read in a string. They are all connected when using string.join in the program.

3. Using the StreamReader.ReadLine() method

There is also a way to read files line by line through the StreamReader class. The method is StreamReader.ReadLine(). This will run to the end of the file.

It works by reading a line of text from the current stream and returning it as a string. This returns the next line in the input stream, or null if the input stream has ended. This way it reaches the end of the file.

If any I/O errors occur, an I/O exception will also occur. Another exception is OutOfMemoryException, which occurs when there is not enough memory to create a buffer for the returned string.

algorithm

The algorithm below will give the step-by-step process of reading the file content line by line using the StreamReader.ReadLine() method.

下面讨论的算法将引导我们创建程序。

第 1 步  创建一个字符串来存储文件路径的名称,记住这是一个绝对路径。

第 2 步 −  创建一个新的读取来读取文件的内容。

第 3 步  while 循环运行到文件末尾。当它达到 null 时就确定结束。

第 4 步  最终,代码在读取文件内容后退出。

示例

以下是该过程的代码 -

using System;
using System.IO;

public class Example {
   public static void Main() {
      string fileloc = @"D:\ttpt\locew.txt";

      using (StreamReader read = new StreamReader(fileloc)) {
         string line;
         while ((line = read.ReadLine()) != null) {
            Console.WriteLine(line);
         }
      }
   }
}

输出

This is a file.
Hello from tutorials point.

在此方法中,也首先使用文件地址创建一个字符串。然后创建一个读取实例。它通过逐行读取内容到达空值,即文件末尾。

时间复杂度

从这里开始,我们正在逐行读取文件,但要一次性读取。无论使用哪种方法,即 File.ReadLines()、Files.ReadAllLines() 和 StreamReader.ReadLine()。他们所有人都在一次读取文件。所以,这里每个方法的时间复杂度都是O(1)。

结论

在本文中,我们广泛讨论了逐行读取文件内容的 C# 程序。我们了解了如何通过三种不同的方式来完成它。 File 类中的两个函数是 ReadLines() 和 ReadAllLines()。第三个来自 StreamReader 类。然后我们讨论了三种技术的代码和算法。我们希望本文能够帮助您增强有关 C# 的知识。

The above is the detailed content of C# program reads file contents line by line. 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