i




 
Thread Rating:
  • 1 Votes - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Serialize / Deserialize Objects Lists in C#
12-28-2012, 10:32 AM
Post: #1
Serialize / Deserialize Objects Lists in C#
The fastest way to Serialize and Deserialize an object of any type is to use DataContractSerializer class in .NET.

Assume you have a class Customer as follows:

Code:
public class Customer {
public string Name {get; set;}
public int Salary {get; set;}
}

And you make a list of objects of that class:

Code:
List<Customer> CustomersList = new List<Customer>();
CustomersList.Add(c1);
CustomersList.Add(c2);
CustomersList.Add(c3);

Now, you want to save this list in your HDD as a file, right? So, lets see how to do that:

Code:
using (FileStream fs = File.Create(@"C:\CustomerList.txt"))
                {
                    DataContractSerializer dcs = new DataContractSerializer(typeof(List<Customer>));
                    XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(fs, Encoding.UTF8);

                    dcs.WriteObject(xdw, CustomersList);
                    xdw.Flush();
                    xdw.Close();
                }

You make a DataContractSerializer object and pass it the type of your object, i.e. List in this case. Then, we make an XmlDictionaryWriter object and pass it the FileStream object along with Encoding Type. Then, simply call DataContractSerializer.WriteObject() instance method and pass it XmlDictionaryWriter and your required object. Don't forget to flush, or Mother C# will be angry. Then close the XmlDictionaryWriter object.

See, how easy is that. Now, what about if you want to retrieve it back and load it into memory? Don't worry, its more simple than it looks. Lets see the following code:

Code:
DataContractSerializer dcs = new DataContractSerializer(typeof(List<Customer>));
                fs = new FileStream(@"C:\CustomerList.txt", FileMode.Open);
                XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
                return (List<Customer>)dcs.ReadObject(reader);

That was the story of Serializing and Deserializing an object in C#. Hope this helps.. Tongue





View Asad Ali's profile on LinkedIn

Quote
12-28-2012, 11:19 AM
Post: #2
RE: Serialize / Deserialize Objects Lists in C#
P.S. this will serialize objects as XML...



View Asad Ali's profile on LinkedIn

Quote
12-28-2012, 06:50 PM
Post: #3
RE: Serialize / Deserialize Objects Lists in C#
Asad, that is very good code demonstration of Serialize / Deserialize object. Keep sharing your experience.

[Image: 2604595733.png]
Quote


Possibly Related Threads...
Thread: Author Replies Views: Last Post
  Why can’t we just use the new operator for creating objects ? Shafiur Rahman 0 1,005 09-21-2010 07:35 AM
Last Post: Shafiur Rahman



User(s) browsing this thread: 1 Guest(s)