Mina Hafzalla
Mina Hafzalla

Reputation: 2821

How to do data serialization in C#?

Working on my project. I have to do data serialization.

I have a code but I don't know how to apply serialization on it.

public class allmethods
{
    private static string Name;
    private static int ID;
    private static int Age;
    private static string Email;
    private static string output;

                public static void WritingMethod()  
          {
                int count = 0;
                while (count < 10)
             {
                    Console.Write(" Enter your Name: ");
                    Name = Console.ReadLine();

                    Console.Write(" Enter your ID: ");
                    ID = int.Parse(Console.ReadLine());

                    Console.Write(" Enter your Age: ");
                    Age = int.Parse(Console.ReadLine());

                    Console.Write(" Enter your E-mail: ");
                    Email = Console.ReadLine();



                    StreamWriter Sw = new StreamWriter("fileone.txt", true);
                    string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
                    + Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
                    Console.WriteLine(output);      
                    Sw.WriteLine(output + Environment.NewLine);
                    Console.ReadLine();

                    Sw.Close();
                    count++;
             }
         }
     }

I'd be glad if anyone helped me with this. Thank you.

Upvotes: 0

Views: 294

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1062895

The first thing you need to do is get rid of those static fields; most serializers work on objects... so let's create a class:

public class Person
{
    public string Name { get; set; }
    public int ID { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

so our main logic becomes:

var person = new Person();
Console.Write(" Enter your Name: ");
person.Name = Console.ReadLine();

Console.Write(" Enter your ID: ");
person.ID = int.Parse(Console.ReadLine());

Console.Write(" Enter your Age: ");
person.Age = int.Parse(Console.ReadLine());

Console.Write(" Enter your E-mail: ");
person.Email = Console.ReadLine();

Next we need to ask - "what serialization format do we want?". It looks like you are appending. Normally I'd say "start with something simple like XmlSerializer or JSON", but neither of those is appendable. BinaryFormatter is IMO universally a bad choice (with very few exceptions). I'm somewhat biased, but one example of a simple-to-use appendable serialization format is protocol-buffers, so I'll use that - note that this is a binary format, but simple to use. The first thing we need to do is add (probably via the nuget package manager in visual studio) protobuf-net. Then we need to tell it how to handle our types, which we do by annotation:

[ProtoContract]
public class Person
{
    [ProtoMember(1)] public string Name { get; set; }
    [ProtoMember(2)] public int ID { get; set; }
    [ProtoMember(3)] public int Age { get; set; }
    [ProtoMember(4)] public string Email { get; set; }
}

Now we change our writing code to use the serializer (in an appendable way):

using (var file = File.Open("fileone.bin", FileMode.Append))
{
    Serializer.SerializeWithLengthPrefix(file, person,
        PrefixStyle.Base128, Serializer.ListItemTag);
}

and then to prove we can read them back at the end:

using (var file = File.OpenRead("fileone.bin"))
{
    foreach(var person in Serializer.DeserializeItems<Person>(
        file, PrefixStyle.Base128, Serializer.ListItemTag))
    {
        Console.WriteLine("{0}, {1}, {2}, {3}",
            person.ID, person.Name, person.Age, person.Email);
    }
}

Upvotes: 1

Rok
Rok

Reputation: 705

Have a look at these examples from a book C# in a Nutshell. Reading the chapter on serialization would also help.

Upvotes: 1

LightStriker
LightStriker

Reputation: 21004

Serialization and deserialization is a very large topic and won't fit a single question.

However, since you're asking where to start, I would suggest you research the ISerializable interface.

http://msdn.microsoft.com/en-CA/library/system.runtime.serialization.iserializable.aspx

Good luck.

Upvotes: 1

Related Questions