C# Read File
Learn how to read files in C#
📖 Reading Files in C#
C# provides simple methods to read file content. Using the File class from System.IO namespace, you can easily read text files, process data, and handle file operations efficiently.
// Simple file reading
using System.IO;
string content = File.ReadAllText("myfile.txt");
Console.WriteLine(content);
Output:
Hello, this is the content of myfile.txt!
Understanding File Reading in C#
File reading is essential for working with stored data. C# offers multiple methods to read files: reading all content at once, reading line by line, or reading in chunks. Each method suits different scenarios, from small text files to large data files requiring efficient memory management.
ReadAllText
Read entire file as string
string text =
File.ReadAllText("file.txt");
ReadAllLines
Read file as array of lines
string[] lines =
File.ReadAllLines("file.txt");
StreamReader
Read file line by line
using StreamReader sr =
new StreamReader("file.txt");
string line = sr.ReadLine();
File.Exists
Check if file exists
if (File.Exists("file.txt"))
{
// Read file
}
🔹 Read Entire File Content
Reading an entire file's content at once in C# is the simplest approach for small to medium files. The File.ReadAllText(path) method returns the complete text as a single string. It's convenient but memory-intensive for large files. Ensure the file path is correct and handle FileNotFoundException and IOException. Use this for configuration files, small data files, or documents.
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
// Read all text from file
string filePath = "example.txt";
string content = File.ReadAllText(filePath);
// Display the content
Console.WriteLine("File Content:");
Console.WriteLine(content);
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Output:
File Content: Hello World! This is a sample text file. Learning C# is fun!
🔹 Read File Line by Line
Reading a file line by line in C# is memory-efficient, especially for large files, as it doesn't load everything at once. Use File.ReadLines(path) which returns an IEnumerable, or StreamReader.ReadLine() in a loop. This allows processing each line individually, reducing memory overhead. Ideal for log files, CSV data, or any large textual data where immediate full content isn't necessary.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "data.txt";
// Check if file exists
if (File.Exists(filePath))
{
// Read all lines into an array
string[] lines = File.ReadAllLines(filePath);
Console.WriteLine($"Total lines: {lines.Length}\n");
// Display each line with line number
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine($"Line {i + 1}: {lines[i]}");
}
}
else
{
Console.WriteLine("File does not exist!");
}
}
}
Output:
Total lines: 3 Line 1: First line of text Line 2: Second line of text Line 3: Third line of text
🔹 Using StreamReader
StreamReader in C# provides granular control for reading text files, offering methods for characters, lines, or blocks. Instantiate it with a file path or stream, then use ReadLine(), ReadToEnd(), or Read(). Always dispose of it via using to release resources. StreamReader supports different encodings and is versatile for complex file reading scenarios beyond simple text.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "log.txt";
try
{
// Using statement ensures proper disposal
using (StreamReader reader = new StreamReader(filePath))
{
string line;
int lineNumber = 1;
// Read line by line until end of file
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine($"{lineNumber}: {line}");
lineNumber++;
}
}
}
catch (IOException ex)
{
Console.WriteLine($"Error reading file: {ex.Message}");
}
}
}
Output:
1: Application started 2: User logged in 3: Data processed successfully 4: Application closed
🔹 Read File with Error Handling
Implementing error handling when reading files in C# prevents crashes from common issues like missing files or access denied. Wrap file operations in try-catch blocks to catch FileNotFoundException, DirectoryNotFoundException, IOException, and UnauthorizedAccessException. Provide user-friendly messages or fallback actions. This robustness is essential for professional applications dealing with external files.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "config.txt";
try
{
// Check if file exists first
if (!File.Exists(filePath))
{
Console.WriteLine($"File '{filePath}' not found!");
return;
}
// Read the file
string content = File.ReadAllText(filePath);
// Check if file is empty
if (string.IsNullOrWhiteSpace(content))
{
Console.WriteLine("File is empty!");
}
else
{
Console.WriteLine("File content:");
Console.WriteLine(content);
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied! Check file permissions.");
}
catch (IOException ex)
{
Console.WriteLine($"IO Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
}
}
Output:
File content: server=localhost port=8080 timeout=30
🔹 Read Specific File Types
Reading specific file types (CSV, XML, JSON) in C# often requires specialized parsers or libraries for correct interpretation. For CSV, use libraries like CsvHelper or manual splitting. For XML, employ XmlDocument or XDocument. For JSON, use Json.NET. Each format has nuances; using dedicated libraries ensures proper handling of encoding, delimiters, schemas, and edge cases.
using System;
using System.IO;
class Program
{
static void Main()
{
// Read CSV file
string csvPath = "data.csv";
if (File.Exists(csvPath))
{
string[] csvLines = File.ReadAllLines(csvPath);
Console.WriteLine("CSV Data:");
foreach (string line in csvLines)
{
string[] values = line.Split(',');
Console.WriteLine(string.Join(" | ", values));
}
}
Console.WriteLine();
// Read text file with specific encoding
string textPath = "document.txt";
if (File.Exists(textPath))
{
string text = File.ReadAllText(textPath,
System.Text.Encoding.UTF8);
Console.WriteLine("Text Document:");
Console.WriteLine(text);
}
}
}
Output:
CSV Data: Name | Age | City John | 25 | New York Jane | 30 | London Text Document: This is a UTF-8 encoded document.