File Input/Output (I/O)
Introduction to File I/O
File Input/Output (I/O) operations in .NET allow reading from and writing to files on disk. .NET provides several classes in the System.IO
namespace to handle file operations.
Reading from a File
To read from a file in .NET, you can use classes like StreamReader
or File
class methods such as ReadAllText
or ReadAllLines
.
Example: Reading from a Text File
string path = @"C:\path\to\file.txt";
string content;
using (StreamReader reader = new StreamReader(path)) {
content = reader.ReadToEnd();
Console.WriteLine(content);
}
Writing to a File
To write to a file in .NET, you can use classes like StreamWriter
or File
class methods such as WriteAllText
or AppendAllText
.
Example: Writing to a Text File
string path = @"C:\path\to\file.txt";
string content = "Hello, File I/O in .NET!";
using (StreamWriter writer = new StreamWriter(path, true)) {
writer.WriteLine(content);
}
Working with Binary Files
In addition to text files, .NET supports reading from and writing to binary files using classes like BinaryReader
and BinaryWriter
.
Example: Reading from and Writing to Binary File
string binPath = @"C:\path\to\binaryfile.dat";
// Writing to binary file
using (BinaryWriter writer = new BinaryWriter(File.Open(binPath, FileMode.Create))) {
writer.Write(1.23);
writer.Write("Hello, binary world!");
}
// Reading from binary file
using (BinaryReader reader = new BinaryReader(File.Open(binPath, FileMode.Open))) {
double num = reader.ReadDouble();
string text = reader.ReadString();
Console.WriteLine(num);
Console.WriteLine(text);
}
Handling File Exceptions
When performing file I/O operations, it's essential to handle exceptions such as file not found, access denied, or I/O errors to ensure robust application behavior.
Example: Handling File Exceptions
try {
string filePath = @"C:\path\to\nonexistentfile.txt";
string content = File.ReadAllText(filePath);
Console.WriteLine(content);
}
catch (FileNotFoundException ex) {
Console.WriteLine("File not found: " + ex.Message);
}
catch (IOException ex) {
Console.WriteLine("An error occurred: " + ex.Message);
}
Conclusion
File Input/Output (I/O) operations are fundamental in .NET for reading from and writing to files. Understanding these concepts and effectively using file handling classes ensures efficient data management in applications.