File IO
File I/O (input/output) in C# allows you to read from and write to files on the disk. This is essential for many applications that need to store data persistently. C# provides classes within the System.IO namespace to handle file operations such as reading, writing, creating, and deleting files.
Key Classes for File I/O
- File: Provides static methods for creating, copying, deleting, moving, and opening files, as well as for reading from and writing to a file.
- FileInfo: Provides instance methods for creating, copying, deleting, moving, and opening files.
- StreamReader: Used for reading characters from a byte stream.
- StreamWriter: Used for writing characters to a stream.
Example
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Writing to a file
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, World!");
writer.WriteLine("This is a sample text file.");
}
Console.WriteLine("Data written to file successfully.");
// Reading from a file
using (StreamReader reader = new StreamReader(filePath))
{
string content = reader.ReadToEnd();
Console.WriteLine("File Content:\n" + content);
}
}
}
Explanation of the Example
- Writing to a File:
- We use a StreamWriter object to write text data to a file.
- The using statement ensures that the StreamWriter object is properly disposed of after use.
- We specify the file path (example.txt) and write two lines of text to the file using WriteLine.
- Reading from a File:
- We use a StreamReader object to read text data from the file.
- The using statement ensures that the StreamReader object is properly disposed of after use.
- We read the entire content of the file using ReadToEnd and print it to the console.
Key Points
- File Path: The ‘filePath’ variable indicates the location of the file. In this example, it is set to “example.txt”, which is relative to the application’s working directory.
- Safe Resource Management: The ‘using’ statement is employed to ensure that both ‘StreamWriter’ and ‘StreamReader’ objects are disposed of properly. This practice is essential for releasing file handles and preventing resource leaks.
- Exception Handling: In real-world applications, it is advisable to incorporate exception handling using try-catch blocks. This helps manage potential I/O errors, such as files not being found or permission issues.
Benefits of File I/O
- Data Persistence: File I/O enables your application to store data persistently, allowing you to save and load data across different sessions.
- Data Sharing: Files can be easily shared between different applications and systems, promoting data exchange and interoperability.
- Backup and Recovery:Writing data to files helps create backups and supports data recovery mechanisms in the event of application failures or data corruption.
