C# File I/O Operations Explained
Overview
This code demonstrates four different file I/O scenarios in C#:
- Text Writing - Writing simple text to a file
- Text Reading - Reading text from a file
- Object Serialization - Writing objects to a file
- Object Deserialization - Reading objects from a file
1. Simple Text Write Operation
Code Breakdown:
string path = "D:\\\\KaradDotNetDemos\\\\Data\\\\Sample.txt";
FileStream fs = null;
if (File.Exists(path))
{
fs = new FileStream(path, FileMode.Append, FileAccess.Write);
}
else
{
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
}
StreamWriter pen = new StreamWriter(fs);
Console.WriteLine("Enter something");
string someData = Console.ReadLine();
pen.WriteLine(someData);
pen.Close();
fs.Close();
Key Concepts:
- FileStream: Low-level file access
- StreamWriter: High-level text writing wrapper
- FileMode.Append: Adds to existing file
- FileMode.Create: Creates new file (overwrites if exists)
- Resource Management: Always close streams to free resources
Flow:
- Check if file exists
- Open file in appropriate mode (Append or Create)