[C#] C# File Operation & Serialization

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in the c# course and tutorial!

  • Course “Programming 2”
  • GeeksforGeeks Tutorial


File Operation(File Handling)

A file is a collection of data stored in a disk with a specific name and a directory path.

The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, and appending the file, etc.

Two basic operation which is mostly used in file handling is reading and writing of the file. The file becomes stream when we open the file for writing and reading.

A stream is a sequence of bytes which is used for communication. Two stream can be formed from file one is input stream which is used to read the file and another is output stream is used to write in the file.

In C#, System.IO namespace contains classes which handle input and output streams and provide information about file and directory structure.

StreamWriter Class and StreamReader Class are the useful for writing in and reading from the text file!!! It will be explained below!!!⬇️

StreamWriter Class

The StreamWriter class implements TextWriter for writing character to stream in a particular format. The class contains the following method which are mostly used.

Method Description
Close() Closes the current StreamWriter object and stream associate with it
Flush() Clears all the data from the buffer and write it in the stream associate with it
Write() Write data to the stream. It has different overloads for different data types to write in stream
WriteLine() It is same as Write() but it add the newline character at the end of the data


using System;
using System.IO;
using System.IO.Pipes;
namespace Comp123
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new
           FileStream(@"c:\users\meena\OneDrive\Desktop\books.txt", FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            string ans = "Y";
            while (ans == "Y" || ans == "y")
            {
                Console.WriteLine("Enter book Id");
                string id = Console.ReadLine();
                Console.WriteLine("Enter book Title");
                string title = Console.ReadLine();
                Console.WriteLine("Enter book Author");
                string author = Console.ReadLine();
                String line = $"{id},{title},{author}";
                sw.WriteLine(line);
                Console.Write("Do you want to enter more books: Y/N ");
                ans = Console.ReadLine();
            }
            sw.Close();
            fs.Close();
            FileStream fs1 = new FileStream(@"c:\users\meena\OneDrive\Desktop\books.txt", FileMode.Open);
            StreamReader sr = new StreamReader(fs1);
            String Line = sr.ReadLine();
            while (Line != null)
            {
                String[] cols = Line.Split(',');
                Console.WriteLine("Book ID :" + cols[0]);
                Console.WriteLine("Book Title :" + cols[1]);
                Console.WriteLine("Book Author :" + cols[2]);
                Line = sr.ReadLine();
            }
            sr.Close();
            fs1.Close();
        }
    }
}


C# I/O Classes

The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.

The following table shows some commonly used non-abstract classes in the System.IO namespace:

Sr.No. I/O Class & Description
1 BinaryReader
  Reads primitive data from a binary stream.
2 BinaryWriter
  Writes primitive data in binary format.
3 BufferedStream
  A temporary storage for a stream of bytes.
4 Directory
  Helps in manipulating a directory structure.
5 DirectoryInfo
  Used for performing operations on directories.
6 DriveInfo
  Provides information for the drives.
7 File
  Helps in manipulating files.
8 FileInfo
  Used for performing operations on files.
9 FileStream
  Used to read from and write to any location in a file.
10 MemoryStream
  Used for random access to streamed data stored in memory.
11 Path
  Performs operations on path information.
12 StreamReader
  Used for reading characters from a byte stream.
13 StreamWriter
  Is used for writing characters to a stream.
14 StringReader
  Is used for reading from a string buffer.
15 StringWriter
  Is used for writing into a string buffer.


The FileStream Class

The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.

You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows:

FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>,
   <FileAccess Enumerator>, <FileShare Enumerator>);

For example, we create a FileStream object F for reading a file named sample.txt as shown:

FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read,
   FileShare.Read);
Sr.No. Parameter & Description
1 FileMode
  The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
  - Append: It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
  - Create: It creates a new file.
  - CreateNew: It specifies to the operating system, that it should create a new file.
  - Open: It opens an existing file.
  - OpenOrCreate: It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
  - Truncate: It opens an existing file and truncates its size to zero bytes.
2 FileAccess
  FileAccess enumerators have members: Read, ReadWrite and Write.
3 FileShare
  FileShare enumerators have the following members:
  - Inheritable: It allows a file handle to pass inheritance to the child processes
  - None: It declines sharing of the current file
  - Read: It allows opening the file for readin.
  - ReadWrite: It allows opening the file for reading and writing
  - Write: It allows opening the file for writing

Example

The following program demonstrates use of the FileStream class:

using System;
using System.IO;

namespace FileIOApplication {
   class Program {
      static void Main(string[] args) {
         FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
            FileAccess.ReadWrite);

         for (int i = 1; i <= 20; i++) {
            F.WriteByte((byte)i);
         }
         F.Position = 0;
         for (int i = 0; i <= 20; i++) {
            Console.Write(F.ReadByte() + " ");
         }
         F.Close();
         Console.ReadKey();
      }
   }
}

//Output:
//1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

EX) Filestream fs = File.Create(pathname);

using System;
using System.IO;
class Program
{
    static void Main()
    {
        string pathName = @"C:\C#\myFile.txt"; //specify path
        FileStream fs = File.Create(pathName); // Create() creates a file at pathName
        if (File.Exists(pathName))
        {
            Console.WriteLine("File is created.");
        }
        else
        {
            Console.WriteLine("File is not created.");
        }
    }
}

EX) CreateText();

using System;
using System.IO;
class Test
{
    public static void Main()
    {
        string path = @"C:\Users\meena\OneDrive\Desktop\hi.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }
        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path))
        {
            string s;
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}

Destructor → Deallocate memory


Advanced File Operations in C#

The preceding example provides simple file operations in C#. However, to utilize the immense powers of C# System.IO classes, you need to know the commonly used properties and methods of these classes.

Sr.No. Topic & Description
1 Reading from and Writing into Text files
  It involves reading from and writing into text files. The StreamReader and StreamWriter class helps to accomplish it.
2 Reading from and Writing into Binary files
  It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class helps to accomplish this.
3 Manipulating the Windows file system
  It gives a C# programmer the ability to browse and locate Windows files and directories.


Serialization in C#: objects → data

Serialization in C# is the process of bringing an object into a form that it can be written on stream. It’s the process of converting the object into a form so that it can be stored on a file, database, or memory; or, it can be transferred across the network. Its main purpose is to save the state of the object so that it can be recreated when needed.

//Serializable
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
    [Serializable]
    class Tutorial
    {
        public int ID;
        public String Name;
        static void Main(string[] args)
        {
            Tutorial obj = new Tutorial();
            obj.ID = 1;
            obj.Name = "C# Programming";
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(@"c:\users\meena\OneDrive\Desktop\test.txt", FileMode.Create,
           FileAccess.Write);
            formatter.Serialize(stream, obj);
            stream.Close();
            stream = new FileStream(@"c:\users\meena\OneDrive\Desktop\test.txt", FileMode.Open,
           FileAccess.Read);
            Tutorial objnew = (Tutorial)formatter.Deserialize(stream);
            Console.WriteLine(objnew.ID);
            Console.WriteLine(objnew.Name);
            Console.ReadKey();
        }
    }
}

Introduction to C# Serialization

The process by which the object instance is converted into a data stream is called serialization and the state of the object instance is converted into data stream because it can be transported across different networks made to be persisted in a location of storage. This serves as an advantage of serialization to transmit the converted data stream across different networks in a format compatible on cross platforms and saves the converted stream data into a medium of storage in a persistent or non-persistent object state so that the same copy can be created in the later time.

Steps of C# Serialization Object

Given below are the steps of C# Serialization Object:

  • A stream object is created.
  • A BinaryFormatter object is created.
  • Serialize( ) method is called.

Working of C# Serialization

Whenever we are working with applications, it is necessary to store the data in a medium which is either persistent or non-persistent so that the same data can be retrieved later. This can be achieved by using the concept of Serialization.

Serialization is essential to transmit the object across the network to cross platforms in a compatible format.

A clone of an object can also be created using Serialization.

Runtime.Serialization namespace must be included in the program to make use of Serialization in C#.

[ Serializable ] attribute is used to make a class Serializable in C#.

An example class to demonstrate [ Serializable ] class

[Serializable]
public class Check
{
   public int code;
   public string name;
}

Similarly, if we want to make any members of the class non-serializable, we can use [ NonSerialized() ] attribute.

Consider the example class below to demonstrate [ NonSerialized() ] attribute:

[Serializable]
public class Check
{
`public int code;
public string name;
[NonSerialized()]
public double price;`
}


Types of Serialization

  • Binary Serialization
  • SOAP Serialization
  • XML Serialization
  • JSON Serialization

1. Binary Serialization

The fastest of all the techniques of serialization is Binary serialization.

An object can be serialized to a binary stream using Binary Serialization.

The identity of the object is preserved while the object is serialized to an output stream using binary serialization.

System.Runtime.Serialization.Formatters.Binary namespace must be included in the program to make use of binary serialization.

2. SOAP Serialization

Simple Object Access Protocol is the abbreviation of SOAP.

We use Simple Object Access Protocol Serialization if we have to transfer the objects from one application to other application which are made of architectures that are heterogeneous.

Portability is the main benefit of using Simple Object Access Protocol Serialization.

An object can be serialized in the form of Simple Object Access Protocol using Simple Object Access Protocol Serialization.

System.Runtime.Serialization.Formatters.Soap namespace must be included in the program to make use of Simple Object Access Protocol serialization.

3. XML Serialization

The public members of the instance of a class can be serialized into an XML stream using XML Serialization.

The speed of XML Serialization is very slower when compared to the speed of binary Serialization.

Cross-platform support is provided by using XML Serialization.

  • XML Serialization is based on text.
  • XML Serialization is easily readable.
  • XML Serialization is easily editable.

A property can be set on XmlAttribute to serialize the property using XML Serialization


Code of Serialization

//C# program to demonstrate the concept of Serialization.
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

//a namespace called demo is created
namespace Demo
{
    //Serializable attribute is declared
    [Serializable]
    //a class check is defined which will be used for serialization
    class Check
    {
        public int identity;
        public String nam;
        static void Main(string[] args)
        {
            //an object of the check class is created to serialize it to the file Example.txt
            Check ob = new Check();
            ob.identity = 10;
            ob.nam = "Shobha";
            //a file stream is created
            IFormatter format = new BinaryFormatter();
            Stream stream1 = new
            FileStream(@"E:\Example.txt", FileMode.Create, FileAccess.Write);
            //serialization of the object of the class check is done
            format.Serialize(stream1, ob);
            stream1.Close();
            //a file stream is created
            stream1 = new FileStream(@"E:\Example.txt", FileMode.Open, FileAccess.Read);
            //the object of the class check is deserialized
            Check ob1 = (Check)format.Deserialize(stream1);
            //the data is written to the console
            Console.WriteLine(ob1.identity);
            Console.WriteLine(ob1.nam);
            Console.ReadKey();
        }
    }
}
//Program to implement Serializable concept
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Demo
{
    //Serializable attribute is declared
    [Serializable]
    //a class check is defined which will be used for serialization
    class Check
    {
        public int identity;
        public String name;
        static void Main(string[] args)
        {
            //an object of the check class is created to serialize it to the file Example.txt
            Check ob = new Check();
            ob.identity = 10;
            ob.name = "Yuvaraj";

            //a file stream is created
            IFormatter format = new BinaryFormatter();
            Stream stream1 = new FileStream(@"C:\Users\meena\OneDrive\Desktop\Example.txt", FileMode.Create, FileAccess.Write);

            //serialization of the object of the class check is done
            format.Serialize(stream1, ob);
            stream1.Close();

            //a file stream is created
            stream1 = new FileStream(@"C:\Users\meena\OneDrive\Desktop\Example.txt", FileMode.Open, FileAccess.Read);

            //the object of the class check is deserialized
            Check ob1 = (Check)format.Deserialize(stream1);
            //the data is written to the console
            Console.WriteLine(ob1.identity);
            Console.WriteLine(ob1.name);
            Console.ReadKey();
        }
    }
}


What is Deserialization in C#?: data → objects

As the name suggests, deserialization in C# is the reverse process of serialization. It is the process of getting back the serialized object so that it can be loaded into memory. It resurrects the state of the object by setting properties, fields etc.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace DemoApplication
{
    [Serializable]
    class Tutorial
    {
        public int ID;
        public string Name;

        static void Main(string[] args)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(@"C:\Users\hijan\OneDrive\바탕 화면\test.txt", FileMode.Open, FileAccess.Read);
            Tutorial objnew = (Tutorial)formatter.Deserialize(stream);
            stream.Close();

            Console.WriteLine(objnew.ID);
            Console.WriteLine(objnew.Name);
            Console.ReadKey();
        }
    }
}




Back to Top

See other articles in Category CS

Leave a comment