File Handling and Serialization in C#
File handling and serialization are essential aspects of C# programming that allow you to work with files and convert objects into a format that can be easily stored or transmitted. Understanding these concepts is crucial for building applications that require data persistence and interoperability.
1. File Handling
File handling in C# involves reading from and writing to files. The System.IO
namespace provides classes and methods to perform file operations. Key classes include File
, FileInfo
, StreamReader
, and StreamWriter
.
Example: Writing to a File
using System; using System.IO; class Program { static void Main() { string path = "example.txt"; string content = "Hello, World!"; File.WriteAllText(path, content); Console.WriteLine("File written successfully."); } }
In this example, the File.WriteAllText
method writes the string content
to the file specified by path
.
Example: Reading from a File
using System; using System.IO; class Program { static void Main() { string path = "example.txt"; string content = File.ReadAllText(path); Console.WriteLine("File content: " + content); } }
In this example, the File.ReadAllText
method reads the entire content of the file specified by path
and stores it in the content
string.
2. Serialization
Serialization is the process of converting an object into a format that can be easily stored or transmitted. Deserialization is the reverse process of reconstructing the object from its serialized form. C# provides the System.Runtime.Serialization
namespace for handling serialization.
Example: Binary Serialization
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; [Serializable] class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { Person person = new Person { Name = "John", Age = 30 }; BinaryFormatter formatter = new BinaryFormatter(); using (FileStream stream = new FileStream("person.dat", FileMode.Create)) { formatter.Serialize(stream, person); } Console.WriteLine("Object serialized successfully."); } }
In this example, the Person
class is marked with the [Serializable]
attribute, allowing it to be serialized. The BinaryFormatter
class is used to serialize the person
object to a binary file.
Example: Binary Deserialization
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; class Program { static void Main() { BinaryFormatter formatter = new BinaryFormatter(); using (FileStream stream = new FileStream("person.dat", FileMode.Open)) { Person person = (Person)formatter.Deserialize(stream); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } } }
In this example, the BinaryFormatter
class is used to deserialize the person
object from the binary file.
3. JSON Serialization
JSON (JavaScript Object Notation) is a lightweight data interchange format. C# provides the System.Text.Json
namespace for JSON serialization and deserialization.
Example: JSON Serialization
using System; using System.Text.Json; class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { Person person = new Person { Name = "John", Age = 30 }; string json = JsonSerializer.Serialize(person); Console.WriteLine("JSON: " + json); } }
In this example, the JsonSerializer.Serialize
method converts the person
object to a JSON string.
Example: JSON Deserialization
using System; using System.Text.Json; class Program { static void Main() { string json = "{\"Name\":\"John\",\"Age\":30}"; Person person = JsonSerializer.Deserialize<Person>(json); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } }
In this example, the JsonSerializer.Deserialize
method converts the JSON string back to a Person
object.
4. XML Serialization
XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. C# provides the System.Xml.Serialization
namespace for XML serialization and deserialization.
Example: XML Serialization
using System; using System.IO; using System.Xml.Serialization; [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { Person person = new Person { Name = "John", Age = 30 }; XmlSerializer serializer = new XmlSerializer(typeof(Person)); using (TextWriter writer = new StreamWriter("person.xml")) { serializer.Serialize(writer, person); } Console.WriteLine("Object serialized to XML successfully."); } }
In this example, the XmlSerializer
class is used to serialize the person
object to an XML file.
Example: XML Deserialization
using System; using System.IO; using System.Xml.Serialization; class Program { static void Main() { XmlSerializer serializer = new XmlSerializer(typeof(Person)); using (TextReader reader = new StreamReader("person.xml")) { Person person = (Person)serializer.Deserialize(reader); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } } }
In this example, the XmlSerializer
class is used to deserialize the person
object from the XML file.
5. File Streams
File streams in C# allow you to read from and write to files in a more controlled manner. The FileStream
class provides methods to read and write data in binary format.
Example: Writing to a File Using FileStream
using System; using System.IO; class Program { static void Main() { string path = "example.dat"; byte[] data = { 1, 2, 3, 4, 5 }; using (FileStream stream = new FileStream(path, FileMode.Create)) { stream.Write(data, 0, data.Length); } Console.WriteLine("Data written successfully."); } }
In this example, the FileStream
class is used to write a byte array to a file.
Example: Reading from a File Using FileStream
using System; using System.IO; class Program { static void Main() { string path = "example.dat"; byte[] data = new byte[5]; using (FileStream stream = new FileStream(path, FileMode.Open)) { stream.Read(data, 0, data.Length); } Console.WriteLine("Data read: " + string.Join(", ", data)); } }
In this example, the FileStream
class is used to read a byte array from a file.
Conclusion
File handling and serialization are fundamental skills for any C# developer. By mastering these concepts, you can create applications that can read from and write to files, as well as serialize and deserialize objects in various formats. This enables you to build more robust and flexible applications that can interact with external data sources and persist data across sessions.