Home >Backend Development >C++ >What's the Most Efficient Way to Read a Text File Line by Line in C#?
C#efficiently read text files
When handling text files in C#, it is important to read it efficiently. The commonly used method is to use to parse files by line. However, in order to improve performance, there are several other technologies worth considering.
<.> 1. StreamReader with the buffer: StreamReader.ReadLine()
The default buffer size is 1024 bytes. Increasing this value can significantly improve performance, especially for large files. Consider using the following code setting buffer size:
<.> 2. File.readlines: StreamReader
<code class="language-csharp">using (var fileStream = File.OpenRead(fileName)) using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, 128)) { string line; while ((line = streamReader.ReadLine()) != null) { // 处理每一行 } }</code>. It is loaded on demand to minimize memory consumption:
<.> 3. File.readalllines:
StreamReader.ReadLine()
This method returns all the array of all rows, but compared with
<code class="language-csharp">var lines = File.ReadLines(fileName); foreach (var line in lines) // 处理每一行</code>
<.> 4. String.split:
The use of The most efficiency of the division line, especially for large documents. It needs to load the entire file into the memory and allocate a array for all rows: File.ReadLines
<code class="language-csharp">var lines = File.ReadAllLines(fileName); for (var i = 0; i < lines.Length; i++) // 处理每一行</code>Recommended method:
In order to obtain the best performance, it is recommended to use
because it has a balance between speed and memory efficiency. If you need a specific file sharing option, you can consider using the with the size of the buffer. String.Split
The above is the detailed content of What's the Most Efficient Way to Read a Text File Line by Line in C#?. For more information, please follow other related articles on the PHP Chinese website!