SlideShare a Scribd company logo
2
Most read
Serialization using C#
By Salman Mushtaq Page 1
Serialization
using C#
December 2
2015
When we want to write or read data from files and database, we do not do
this directly. Because object is not automatically converted. Casting is not
useful here. So, that’s why we use serialization for doing it correctly.
Reading &
Writing
objects using
serialization
Serialization using C#
By Salman Mushtaq Page 2
Asalam U Alaikum all readers!
I am Salman and today we discuss about Serialization in C#.
Suppose we have a small project. In project you develop a module and you need to save objects into
files. What can you do? Exactly you use some classes of System.IO like FileStream, StreamWriter and
StreamReader.
So, you make an object and write it to file. But when you see the file data it just Namespace.FileName.
You think what the wrong here is. Similarly when you try to read data you receive exception.
So here we need serialization. Serialization is used where we need to write object to database or file.
And vice versa. See the below diagram.
According to diagram. We have object and with the help of serialization object converts into bytes then
it saves to memory, database or file.
Now what we need to do all this.
- Class/Object for serialization
- A stream to serialized object
- Formatter
- Namespace: System.Runtime.Serialization
- Interface: ISerializable
Now, we write some code and explain it to you.
See code on start on next page.
Serialization using C#
By Salman Mushtaq Page 3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace TestObjectWritingInTextfile
{
[Serializable()]
class Worker : ISerializable
{
public string name;
public string phone;
// Default constructor
public Worker()
{
name = null;
phone = null;
}
// Parameterized constructor
public Worker(string name, string phone)
{
this.name = name;
this.phone = phone;
}
public Worker(SerializationInfo info, StreamingContext ctxt)
{
name = (string)info.GetValue("Name", typeof(string));
phone = (string)info.GetValue("Phone", typeof(string));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Name", name);
info.AddValue("Phone", phone);
}
}
public class Contact
{
public static void Main(String[] args)
{
Worker obj = new Worker("Salman Mushtaq", "03337465571");
//For writing data
Stream sw = File.Open(@"C:UsersManiDesktopFilesnames.txt",
FileMode.Append);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(sw, obj);
sw.Close();
//For reading data
Serialization using C#
By Salman Mushtaq Page 4
Stream sr = File.Open(@"C:UsersManiDesktopFilesnames.txt",
FileMode.Open);
BinaryFormatter br = new BinaryFormatter();
obj = (Worker)br.Deserialize(sr);
sr.Close();
Console.WriteLine("Name: " + obj.name);
Console.WriteLine("Name: " + obj.phone);
Console.ReadKey();
}
}
}
You need three namespaces:
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
First of all you must implement ISerializable interface. It have two function one for Serialization and
second is for De-serialization. Both function have two parameters.
SerializationInfo info, StreamingContext ctxt
Method GetObjectdata is used for writing data. As we know we first convert all data into
bytes so we need formatter. That help us to write or read data on stream.
Hope you understand. If you have some question please email me at salman_1538@hotmail.com

More Related Content

PDF
Payloads and OCR with Solr
PDF
Lecture 3 - ES6 Script Advanced for React-Native
PDF
Vizwik part 2 scripts
PDF
Vizwik Coding Manual
PDF
Vizwik part 3 data
PPTX
Actor-based concurrency and Akka Fundamentals
PPTX
Build JSON and XML using RABL gem
PDF
Dutch hug
Payloads and OCR with Solr
Lecture 3 - ES6 Script Advanced for React-Native
Vizwik part 2 scripts
Vizwik Coding Manual
Vizwik part 3 data
Actor-based concurrency and Akka Fundamentals
Build JSON and XML using RABL gem
Dutch hug

What's hot (6)

PPTX
Java script function
PPTX
Rails best practices
PDF
React with Ref
PDF
Casting Against Type(s)
PPTX
C# advanced topics and future - C#5
Java script function
Rails best practices
React with Ref
Casting Against Type(s)
C# advanced topics and future - C#5
Ad

Viewers also liked (11)

PDF
Periódico institucional cuarto trimestre 2015
PDF
La palabra de incide
PDF
Diafragma pelvico
PPTX
EDRD 6000: Ethics when working with LGBTQ+ Youth
PPTX
Presentación1
PDF
Mistakes in comparative research method
DOCX
Qr kodovi
PPTX
Auditoriasgc
PPTX
How to essay examples
PDF
Méthodes de recherche scientifique sur internet pour rééducateurs
DOC
Perdes LKPJ TA. 2016 Desa Bhuana Jaya
Periódico institucional cuarto trimestre 2015
La palabra de incide
Diafragma pelvico
EDRD 6000: Ethics when working with LGBTQ+ Youth
Presentación1
Mistakes in comparative research method
Qr kodovi
Auditoriasgc
How to essay examples
Méthodes de recherche scientifique sur internet pour rééducateurs
Perdes LKPJ TA. 2016 Desa Bhuana Jaya
Ad

Similar to Serialization (20)

PPTX
Dynamic Language Performance
PPT
Demystifying Maven
DOCX
Unit8 java
PPTX
C++ tutorial assignment - 23MTS5730.pptx
PDF
Ejb3 Struts Tutorial En
PDF
Ejb3 Struts Tutorial En
PDF
create-netflix-clone-02-server_transcript.pdf
PPT
The Theory Of The Dom
PPT
Synapseindia dot net development
PPTX
interface in java explained in detailed form
PPT
Accessing loosely structured data from F# and C#
PPT
iOS Application Development
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
PPTX
Typescript language extension of java script
PDF
C++ Interview Questions and Answers PDF By ScholarHat
PDF
Persistence And Documents
PPTX
Introduction to Core Java Programming
PDF
OOPs Interview Questions PDF By ScholarHat
PDF
Active object of Symbian in the lights of client server architecture
PPT
Red5 - PHUG Workshops
Dynamic Language Performance
Demystifying Maven
Unit8 java
C++ tutorial assignment - 23MTS5730.pptx
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial En
create-netflix-clone-02-server_transcript.pdf
The Theory Of The Dom
Synapseindia dot net development
interface in java explained in detailed form
Accessing loosely structured data from F# and C#
iOS Application Development
Object Oriented Programming (OOP) using C++ - Lecture 1
Typescript language extension of java script
C++ Interview Questions and Answers PDF By ScholarHat
Persistence And Documents
Introduction to Core Java Programming
OOPs Interview Questions PDF By ScholarHat
Active object of Symbian in the lights of client server architecture
Red5 - PHUG Workshops

More from Salman Mushtaq (7)

PDF
Bootstrap 3 Lecture 5
PDF
LINQ to SQL
PDF
PDF
ADO DOT NET
PDF
Contact Book Version 1.0
PDF
Entity frame work by Salman Mushtaq -1-
PDF
Database By Salman Mushtaq
Bootstrap 3 Lecture 5
LINQ to SQL
ADO DOT NET
Contact Book Version 1.0
Entity frame work by Salman Mushtaq -1-
Database By Salman Mushtaq

Serialization

  • 1. Serialization using C# By Salman Mushtaq Page 1 Serialization using C# December 2 2015 When we want to write or read data from files and database, we do not do this directly. Because object is not automatically converted. Casting is not useful here. So, that’s why we use serialization for doing it correctly. Reading & Writing objects using serialization
  • 2. Serialization using C# By Salman Mushtaq Page 2 Asalam U Alaikum all readers! I am Salman and today we discuss about Serialization in C#. Suppose we have a small project. In project you develop a module and you need to save objects into files. What can you do? Exactly you use some classes of System.IO like FileStream, StreamWriter and StreamReader. So, you make an object and write it to file. But when you see the file data it just Namespace.FileName. You think what the wrong here is. Similarly when you try to read data you receive exception. So here we need serialization. Serialization is used where we need to write object to database or file. And vice versa. See the below diagram. According to diagram. We have object and with the help of serialization object converts into bytes then it saves to memory, database or file. Now what we need to do all this. - Class/Object for serialization - A stream to serialized object - Formatter - Namespace: System.Runtime.Serialization - Interface: ISerializable Now, we write some code and explain it to you. See code on start on next page.
  • 3. Serialization using C# By Salman Mushtaq Page 3 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace TestObjectWritingInTextfile { [Serializable()] class Worker : ISerializable { public string name; public string phone; // Default constructor public Worker() { name = null; phone = null; } // Parameterized constructor public Worker(string name, string phone) { this.name = name; this.phone = phone; } public Worker(SerializationInfo info, StreamingContext ctxt) { name = (string)info.GetValue("Name", typeof(string)); phone = (string)info.GetValue("Phone", typeof(string)); } public void GetObjectData(SerializationInfo info, StreamingContext ctxt) { info.AddValue("Name", name); info.AddValue("Phone", phone); } } public class Contact { public static void Main(String[] args) { Worker obj = new Worker("Salman Mushtaq", "03337465571"); //For writing data Stream sw = File.Open(@"C:UsersManiDesktopFilesnames.txt", FileMode.Append); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(sw, obj); sw.Close(); //For reading data
  • 4. Serialization using C# By Salman Mushtaq Page 4 Stream sr = File.Open(@"C:UsersManiDesktopFilesnames.txt", FileMode.Open); BinaryFormatter br = new BinaryFormatter(); obj = (Worker)br.Deserialize(sr); sr.Close(); Console.WriteLine("Name: " + obj.name); Console.WriteLine("Name: " + obj.phone); Console.ReadKey(); } } } You need three namespaces: using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; First of all you must implement ISerializable interface. It have two function one for Serialization and second is for De-serialization. Both function have two parameters. SerializationInfo info, StreamingContext ctxt Method GetObjectdata is used for writing data. As we know we first convert all data into bytes so we need formatter. That help us to write or read data on stream. Hope you understand. If you have some question please email me at salman_1538@hotmail.com