Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

C#.Net

Tutorials – C#.Net

 
Chapter 8: File I/O and Serialization


Chapter 8 of our C# tutorial delves into file I/O (Input/Output) and serialization. File I/O is the process of reading from and writing to files on your computer, while serialization is the process of converting objects into a format that can be easily stored or transmitted. In this chapter, you will learn how to work with files, directories, and how to serialize and deserialize objects in C#.

8.1 File I/O in C#

File I/O is a fundamental part of many applications. It allows you to interact with files and directories, read data from files, and write data to them. C# provides several classes in the System.IO namespace to work with file I/O.

8.1.1 Reading from Files

You can read data from files using the File and StreamReader classes.

Reading Text Files with File.ReadAllText

The File.ReadAllText method allows you to read the entire contents of a text file as a string. Here’s an example:

using System;
using System.IO;
class Program {
static void Main() {
string text = File.ReadAllText("example.txt"); Console.WriteLine(text); } }

This code reads the contents of a file named “example.txt” and prints it to the console.

Reading Text Files with StreamReader

The StreamReader class provides more control when reading text files. It allows you to read line by line or character by character.

using System;
using System.IO;
class Program {
static void Main() {
using (StreamReader reader = new StreamReader("example.txt")) {
string line;
while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }

In this example, we use a StreamReader to read a text file line by line. The using statement ensures that the StreamReader is properly disposed of when done.

8.1.2 Writing to Files

To write data to files, you can use the File and StreamWriter classes.

Writing Text Files with File.WriteAllText

The File.WriteAllText method allows you to write a string to a text file. If the file doesn’t exist, it will be created; if it does exist, its contents will be overwritten.

using System;
using System.IO;
class Program {
static void Main() {
string text = "Hello, File I/O!"; File.WriteAllText("output.txt", text); } }

This code writes the string to a file named “output.txt.”

Writing Text Files with StreamWriter

The StreamWriter class provides more flexibility when writing text files. You can append data to an existing file or choose the encoding.

using System;
using System.IO;
class Program {
static void Main() {
using (StreamWriter writer = new StreamWriter("output.txt", true)) // Append mode { writer.WriteLine("This is a new line of text."); } } }

In this example, we use a StreamWriter to append a new line to an existing text file.

8.1.3 Working with Directories

C# provides classes to work with directories as well. The Directory and DirectoryInfo classes are commonly used for directory-related operations.

Creating a Directory

You can create a directory using the Directory.CreateDirectory method:

using System;
using System.IO;
class Program {
static void Main() { Directory.CreateDirectory("NewDirectory"); } }

This code creates a directory named “NewDirectory” if it doesn’t already exist.

Listing Files in a Directory

You can list the files in a directory using the Directory.GetFiles method:

using System;
using System.IO;
class Program {
static void Main() {
string directoryPath = "SomeDirectory";
string[] files = Directory.GetFiles(directoryPath);
foreach (string file in files) { Console.WriteLine(file); } } }

This code retrieves a list of files in the specified directory and prints their paths to the console.

8.1.4 File and Directory Manipulation

The File and Directory classes provide various methods for file and directory manipulation, such as copying, moving, and deleting.

using System;
using System.IO;
class Program
{
static void Main()
{
string sourceFile = "source.txt";
string destinationFile = "destination.txt";
File.Copy(sourceFile, destinationFile);
File.Move(sourceFile, "moved.txt");
File.Delete("fileToDelete.txt");
string sourceDirectory = "SourceDir";
string destinationDirectory = "DestinationDir";
Directory.CreateDirectory(sourceDirectory);
Directory.CreateDirectory(destinationDirectory);
Directory.Move(sourceDirectory, destinationDirectory);
Directory.Delete("DirectoryToDelete", true); // 'true' means to delete subdirectories
}
}

This code demonstrates how to copy, move, and delete files and directories.

8.2 Serialization in C#

Serialization is the process of converting an object into a format that can be easily stored or transmitted and then reconstructing the object from that format. C# provides built-in mechanisms for serialization, primarily through the System.Runtime.Serialization namespace.

8.2.1 Binary Serialization

Binary serialization converts objects into binary format, which is not human-readable but efficient for data storage and transmission. To use binary serialization, you need to mark the class you want to serialize with the [Serializable] attribute.

Serializing Objects

using System;
using System.IO;
using System.Runtime.Serialization;
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 = "Alice", Age = 30 };
// Serialize the object to a binary file
using (FileStream stream = new FileStream("person.bin", FileMode.Create))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, person);
}
}
}

In this example, we define a Person class and mark it as [Serializable]. We then create an instance of the Person class and serialize it to a binary file.

Deserializing Objects

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// Deserialize the object from a binary file
using (FileStream stream = new FileStream("person.bin", FileMode.Open))
{
IFormatter formatter = new BinaryFormatter();
Person person = (Person)formatter.Deserialize(stream);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}

This code deserializes the object from the binary file and prints the data.

8.2.2 XML Serialization

XML serialization converts objects into XML format, which is human-readable and widely used for data interchange. To use XML serialization, you need to mark the class with the [Serializable] attribute and implement the IXmlSerializable interface.

Serializing Objects

using System;
using System.IO;
using System.Xml.Serialization;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "Bob", Age = 25 };
// Serialize the object to an XML file
using (FileStream stream = new FileStream("person.xml", FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(Person));
serializer.Serialize(stream, person);
}
}
}

In this example, we create an instance of the Person class and serialize it to an XML file.

Deserializing Objects

using System;
using System.IO;
using System.Xml.Serialization;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
// Deserialize the object from an XML file
using (FileStream stream = new FileStream("person.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(Person));
Person person = (Person)serializer.Deserialize(stream);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}

This code deserializes the object from the XML file and prints the data.

8.3 JSON Serialization

JSON (JavaScript Object Notation) serialization is widely used for data exchange between applications. C# provides a built-in mechanism for JSON serialization through the System.Text.Json namespace.

8.3.1 Serializing Objects to JSON

To serialize an object to JSON, you can use the System.Text.Json.JsonSerializer class. You need to specify the type of the object you want to serialize and a Stream where the JSON data will be written.

using System;
using System.IO;
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 = "Charlie", Age = 35 };
// Serialize the object to JSON
using (MemoryStream stream = new MemoryStream())
{
JsonSerializer.Serialize(stream, person);
string json = System.Text.Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(json);
}
}
}

In this example, we create an instance of the Person class and serialize it to a JSON string.

8.3.2 Deserializing JSON into Objects

To deserialize JSON data into C# objects, you can use the System.Text.Json.JsonSerializer class. You need to specify the type of the object you want to deserialize and a Stream containing the JSON data.

using System;
using System.IO;
using System.Text.Json;
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
string json = "{\"Name\":\"David\",\"Age\":40}";
// Deserialize JSON into an object
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
{
Person person = JsonSerializer.Deserialize<Person>(stream);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}

This code deserializes JSON data into a Person object and prints its properties.

8.4 Conclusion of Chapter 8

In Chapter 8, you’ve learned how to perform file I/O and serialization in C#. File I/O allows you to read from and write to files and directories, and serialization enables you to convert objects into a format suitable for storage or transmission.

File I/O includes reading and writing text files, working with directories, and manipulating files and directories. Serialization is achieved using binary, XML, and JSON formats, and each has its use cases.

Understanding these concepts and mastering file I/O and serialization in C# is essential for building data-driven and well-structured applications. Whether you’re working with files, databases, or APIs, the knowledge you’ve gained in this chapter will prove valuable in your C# development journey.

Scroll to Top