SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances (6)

Java script function
Java script functionJava script function
Java script function
 
Rails best practices
Rails best practicesRails best practices
Rails best practices
 
Soap
SoapSoap
Soap
 
React with Ref
React with RefReact with Ref
React with Ref
 
Casting Against Type(s)
Casting Against Type(s)Casting Against Type(s)
Casting Against Type(s)
 
C# advanced topics and future - C#5
C# advanced topics and future - C#5C# advanced topics and future - C#5
C# advanced topics and future - C#5
 

En vedette

Perdes LKPJ TA. 2016 Desa Bhuana Jaya
Perdes LKPJ TA. 2016 Desa Bhuana JayaPerdes LKPJ TA. 2016 Desa Bhuana Jaya
Perdes LKPJ TA. 2016 Desa Bhuana Jaya
Suwondo Chan
 

En vedette (11)

Periódico institucional cuarto trimestre 2015
Periódico institucional cuarto  trimestre 2015Periódico institucional cuarto  trimestre 2015
Periódico institucional cuarto trimestre 2015
 
La palabra de incide
La palabra de incideLa palabra de incide
La palabra de incide
 
Diafragma pelvico
Diafragma pelvicoDiafragma pelvico
Diafragma pelvico
 
EDRD 6000: Ethics when working with LGBTQ+ Youth
EDRD 6000: Ethics when working with LGBTQ+ YouthEDRD 6000: Ethics when working with LGBTQ+ Youth
EDRD 6000: Ethics when working with LGBTQ+ Youth
 
Presentación1
Presentación1Presentación1
Presentación1
 
Mistakes in comparative research method
Mistakes in comparative research methodMistakes in comparative research method
Mistakes in comparative research method
 
Qr kodovi
Qr kodoviQr kodovi
Qr kodovi
 
Auditoriasgc
AuditoriasgcAuditoriasgc
Auditoriasgc
 
How to essay examples
How to essay examplesHow to essay examples
How to essay examples
 
Méthodes de recherche scientifique sur internet pour rééducateurs
Méthodes de recherche scientifique sur internet pour rééducateursMéthodes de recherche scientifique sur internet pour rééducateurs
Méthodes de recherche scientifique sur internet pour rééducateurs
 
Perdes LKPJ TA. 2016 Desa Bhuana Jaya
Perdes LKPJ TA. 2016 Desa Bhuana JayaPerdes LKPJ TA. 2016 Desa Bhuana Jaya
Perdes LKPJ TA. 2016 Desa Bhuana Jaya
 

Similaire à Serialization

Unit8 java
Unit8 javaUnit8 java
Unit8 java
mrecedu
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
Richa Jain
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
Talbott Crowell
 

Similaire à Serialization (20)

Dynamic Language Performance
Dynamic Language PerformanceDynamic Language Performance
Dynamic Language Performance
 
Demystifying Maven
Demystifying MavenDemystifying Maven
Demystifying Maven
 
Unit8 java
Unit8 javaUnit8 java
Unit8 java
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
create-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdfcreate-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdf
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
iOS Application Development
iOS Application DevelopmentiOS Application Development
iOS Application Development
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
 
PostThis
PostThisPostThis
PostThis
 

Plus de Salman Mushtaq

Plus de Salman Mushtaq (7)

Bootstrap 3 Lecture 5
Bootstrap 3 Lecture 5Bootstrap 3 Lecture 5
Bootstrap 3 Lecture 5
 
LINQ to SQL
LINQ to SQLLINQ to SQL
LINQ to SQL
 
Captcha
CaptchaCaptcha
Captcha
 
ADO DOT NET
ADO DOT NETADO DOT NET
ADO DOT NET
 
Contact Book Version 1.0
Contact Book Version 1.0Contact Book Version 1.0
Contact Book Version 1.0
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-
 
Database By Salman Mushtaq
Database By Salman MushtaqDatabase By Salman Mushtaq
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