Introduction:
In this new chapter, we'll explore File I/O and Serialization, essential concepts for working with data in C#. In this first article, we'll discuss reading and writing text and binary files. In the next article, we'll delve into serialization and deserialization of objects, which are important for persisting and restoring object states.
Reading and Writing Text Files:
C# provides several classes for reading and writing text files, such as StreamReader, StreamWriter, and File:
// Writing a text file using (StreamWriter writer = new StreamWriter("example.txt")) { writer.WriteLine("Hello, world!"); } // Reading a text file using (StreamReader reader = new StreamReader("example.txt")) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } }
Reading and Writing Binary Files:
For working with binary files, C# provides the BinaryReader and BinaryWriter classes:
// Writing a binary file using (BinaryWriter writer = new BinaryWriter(File.Open("example.bin", FileMode.Create))) { writer.Write(42); writer.Write("Hello, world!"); } // Reading a binary file using (BinaryReader reader = new BinaryReader(File.Open("example.bin", FileMode.Open))) { int number = reader.ReadInt32(); string text = reader.ReadString(); Console.WriteLine(number); Console.WriteLine(text); }
File Handling Best Practices:
When working with files, it's essential to follow best practices to ensure proper resource management and error handling:
- Use the using statement to automatically close and dispose of file resources.
- Use exception handling (try-catch blocks) to manage potential errors, such as file not found or access denied.
Conclusion:
In this article, we discussed reading and writing text and binary files, essential skills for working with data in C#. Understanding these concepts will help you handle data effectively in your applications. In the next article, we'll delve into serialization and deserialization of objects, important for persisting and restoring object states. Stay tuned for more insights into File I/O and Serialization!
Comments
Post a Comment