C # serialization and deserialization code

Source: Internet
Author: User

Serialization and deserialization are often used in daily development. What do they mean? In general, serialization refers to converting an object into a data file or field (binary or XML). deserialization refers to converting a data file or field into a data object. Below I will explain serialization and deserialization in a way that I can ask a question. (C # code example)

I. Why is serialization and deserialization used?

1. Save the object. Generally, we construct an object in the C # code and save the object to other storage environments such as database, file, application, session, coockie, and viewstate for future use.

2. Shared data. An object is valid only in the application domain of the created object. This technology is used when other application domains want to call the object data.

3. Transmit the object's byte sequence on the network. The Web Service is a typical example.

4. This technology is also frequently used in some distributed systems.

Ii. What types of serialization and deserialization are available?

There are roughly three types of serialization deserialization in C:

First, binary data (binaryformatter-> iformatter)

2. XML data (xmlserializer)

Third, soap data (soapformatter-> iformatter)

Iii. How to Implement serialization and deserialization?   


/// <Summary>
/// Userinfo for public test smaple
/// </Summary>
[Serializable]
Public class userinfo
{

# Region database fields
Private system. int32 _ userid;
Private system. String _ username;
Private system. int16 _ usertype;
Private system. String _ email;
Private system. String _ PWD;
Private system. String _ firstname;
Private system. String _ lastname;
# Endregion

# Region gets and sets

Public System. int32 userid
{
Get {return _ userid ;}
Set {_ userid = value ;}
}

Public System. String Username
{
Get {return _ username ;}
Set {_ username = value ;}
}

Public System. int16 usertype
{
Get {return _ usertype ;}
Set {_ usertype = value ;}
}

Public System. String email
{
Get {return _ email ;}
Set {_ email = value ;}
}

Public System. String pwd
{
Get {return _ PWD ;}
Set {_ Pwd = value ;}
}
Public System. String firstname
{
Get {return _ firstname ;}
Set {_ firstname = value ;}
}

Public System. String lastname
{
Get {return _ lastname ;}
Set {_ lastname = value ;}
}
# Endregion

Public userinfo ()
{
}
}

First, binary data


Public static byte [] serialize (userinfo USR)
{
Iformatter formatter = new binaryformatter ();
Memorystream MS = new memorystream ();
Byte [] B;
Formatter. serialize (MS, USR );
Ms. Position = 0;
B = new byte [Ms. Length];
Ms. Read (B, 0, B. Length );
Ms. Close ();
Return B;
}
Public static userinfo deserialize (byte [] bytearray)
{
Iformatter formatter = new binaryformatter ();
Memorystream MS = new memorystream ();
Ms. Write (bytearray, 0, bytearray. Length );
Ms. Position = 0;
Userinfo USR = formatter. deserialize (MS) as userinfo;
Return USR;
}

Ii. XML data


Public static xmldocument serialize (userinfo USR)
{
Xmlserializer Lizer = new xmlserializer (USR. GetType ());
Memorystream MS = new memorystream ();
Lizer. serialize (MS, USR );
Xmldocument Doc = new xmldocument ();
Doc. Load (MS );
Return Doc;
}
Public static userinfo deserializexml (xmldocument DOC)
{
Xmlserializer Lizer = new xmlserializer (typeof (userinfo ));
Stringreader reader = new stringreader (Doc. outerxml );
Userinfo USR = Lizer. deserialize (Reader) as userinfo;
Return USR;
}

Third, soap data


Static void serialize ()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses = new hashtable ();
Addresses. Add ("Jeff", "123 Main Street, Redmond, WA 98052 ");
Addresses. Add ("Fred", "987 Pine Road, Phila., PA 19116 ");
Addresses. Add ("Mary", "PO Box 112233, Palo Alto, CA 94301 ");

// To serialize the hashtable (and its key/value pairs ),
// You must first open a stream for writing.
// Use a file stream here.
Filestream FS = new filestream ("datafile. Soap", filemode. Create );

// Construct a soapformatter and use it
// To serialize the data to the stream.
Soapformatter formatter = new soapformatter ();
Try
{
Formatter. serialize (FS, addresses );
}
Catch (serializationexception E)
{
Console. writeline ("failed to serialize. Reason:" + E. Message );
Throw;
}
Finally
{
FS. Close ();
}
}


Static void deserialize ()
{
// Declare the hashtable reference.
Hashtable addresses = NULL;

// Open the file containing the data that you want to deserialize.
Filestream FS = new filestream ("datafile. Soap", filemode. Open );
Try
{
Soapformatter formatter = new soapformatter ();

// Deserialize the hashtable from the file and
// Assign the reference to the local variable.
Addresses = (hashtable) formatter. deserialize (FS );
}
Catch (serializationexception E)
{
Console. writeline ("failed to deserialize. Reason:" + E. Message );
Throw;
}
Finally
{
FS. Close ();
}

// To prove that the table deserialized correctly,
// Display the key/value pairs to the console.
Foreach (dictionaryentry de in addresses)
{
Console. writeline ("{0} lives at {1}.", De. Key, De. value );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.