Handling files is a fundamental aspect of many software applications. Whether you're logging information, processing data from external sources, or creating reports, working with text files becomes essential. In this article, we will thoroughly explore Reading and Writing Text Files in C#, including syntax, methods, best practices, and practical examples to help you implement robust file I/O operations in your C# applications.
C# provides a rich set of classes in the System.IO namespace to work with files. These include:
string filePath = "example.txt"; if (File.Exists(filePath)) { string content = File.ReadAllText(filePath); Console.WriteLine(content); } else { Console.WriteLine("File does not exist."); }
string filePath = "output.txt"; string data = "This is a test message."; File.WriteAllText(filePath, data);
using (StreamReader reader = new StreamReader("example.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } }
using (StreamWriter writer = new StreamWriter("output.txt", true)) { writer.WriteLine("Appended line at: " + DateTime.Now); }
If you want to add content to an existing file without overwriting:
File.AppendAllText("log.txt", "New entry at " + DateTime.Now + Environment.NewLine);
try { string data = File.ReadAllText("nonexistent.txt"); Console.WriteLine(data); } catch (FileNotFoundException ex) { Console.WriteLine("Error: File not found - " + ex.Message); } catch (IOException ex) { Console.WriteLine("IO Exception: " + ex.Message); }
For very large files, prefer reading and writing in chunks to avoid memory overflow.
using (FileStream fs = new FileStream("large.txt", FileMode.Open)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) { Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead)); } }
Method | Description |
---|---|
File.ReadAllText() | Reads all content from a file. |
File.WriteAllText() | Writes content to a file, overwriting if it exists. |
File.AppendAllText() | Appends content to an existing file. |
StreamReader.ReadLine() | Reads file line by line. |
StreamWriter.WriteLine() | Writes a line to a file. |
Mastering Reading and Writing Text Files in C# is essential for developers working on any application involving file storage or manipulation. By understanding the different approaches and following best practices, you can ensure your file I/O operations are efficient, safe, and scalable.
Copyrights © 2024 letsupdateskills All rights reserved