File handling is a crucial aspect of most applications, especially when processing data stored externally. This article focuses on Reading Files Line by Line in C#: StreamReader Explained? — a powerful and efficient approach using the StreamReader class in C#. Whether you're reading configuration files, logs, or large data sets, StreamReader offers performance and control.
The StreamReader class is a part of the System.IO namespace in C#. It is designed for character-based file reading and is especially useful when you want to process text files line by line instead of loading the entire file into memory.
using System; using System.IO; class Program { static void Main() { using (StreamReader reader = new StreamReader("example.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
Always wrap file access code in try-catch blocks to manage exceptions like missing files or unauthorized access.
try { using (StreamReader reader = new StreamReader("missing.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } catch (FileNotFoundException ex) { Console.WriteLine("File not found: " + ex.Message); } catch (IOException ex) { Console.WriteLine("IO error: " + ex.Message); }
using (StreamReader reader = new StreamReader("data.txt", Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } }
while ((line = reader.ReadLine()) != null) { if (!string.IsNullOrWhiteSpace(line)) { Console.WriteLine(line); } }
| Method | Description | Best Use Case |
|---|---|---|
| File.ReadAllText() | Reads entire file into a string | Small files |
| File.ReadAllLines() | Reads all lines into an array | Small to medium files |
| StreamReader.ReadLine() | Reads file line by line | Large files |
Reading Files Line by Line in C#: StreamReader Explained? showcases one of the most memory-efficient ways to handle text files in C#. With the ability to read files line-by-line and manage large datasets effectively, StreamReader remains a go-to solution in professional-grade applications. Mastering it enables better performance, more stable code, and scalable solutions for file processing in C#.
Copyrights © 2024 letsupdateskills All rights reserved