Efficiently read specified lines of text files to avoid memory usage
This article introduces several ways to efficiently read specified lines of text files without loading the entire file into memory.
.NET 4.0 and above
.NET 4.0 and higher can use the skip line method:
<code>string line = File.ReadLines(FileName).Skip(14).Take(1).First();</code>
This method reads line 15 directly without loading the entire file into memory.
.NET 4.0 or below
Before .NET 4.0, you need to skip line by line:
<code>string GetLine(string fileName, int line) { using (var sr = new StreamReader(fileName)) { for (int i = 1; i < line; i++) sr.ReadLine(); return sr.ReadLine(); } }</code>
This method only reads the required rows, thus reducing memory consumption.
Notes
While the skip line approach avoids storing the entire file in memory, it may be less efficient for accessing lines near the end of the file. Furthermore, the file structure must allow line numbers to be determined precisely, without relying on line numbers that may vary.
The above is the detailed content of How Can I Efficiently Access a Specific Line in a Text File Without Loading the Entire File into Memory?. For more information, please follow other related articles on the PHP Chinese website!