Read the C#text file method in detail
In the program design, sometimes the text file needs to be read backward. This can be implemented by iterators, which allows sequential processing data without loading the entire file into memory to improve efficiency.
When reading the text file reverse, the encoding method of the file must be considered. For example, if the file uses UTF-8 coding, you need to correctly identify the starting position of each Unicode character and process any invalid UTF-8 sequence.
The following C#code fragment demonstrates how to use the iterator to read the text file:
<code class="language-csharp">using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; public static class ReverseFileStreamReader { public static IEnumerable<string> ReadFileLinesReverse(string filePath) { using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { long fileLength = fileStream.Length; byte[] buffer = new byte[1024]; for (long position = fileLength - buffer.Length; position >= 0; position -= buffer.Length) { fileStream.Seek(position, SeekOrigin.Begin); int bytesRead = fileStream.Read(buffer, 0, buffer.Length); var lines = GetLinesFromBuffer(buffer, bytesRead); foreach (var line in lines) { yield return line; } } } } private static IEnumerable<string> GetLinesFromBuffer(byte[] buffer, int bytesRead) { return new string(GetCharactersFromBuffer(buffer, bytesRead)) .Split('\n') .Reverse(); } private static IEnumerable<char> GetCharactersFromBuffer(byte[] buffer, int bytesRead) { using (var memoryStream = new MemoryStream(buffer, 0, bytesRead)) { using (var streamReader = new StreamReader(memoryStream, Encoding.UTF8)) { while (!streamReader.EndOfStream) { yield return (char)streamReader.Read(); } } } } }</code>
The above is the detailed content of How Can I Efficiently Read a Text File in Reverse Order Using C#?. For more information, please follow other related articles on the PHP Chinese website!