Click here to Skip to main content
16,016,613 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
In my client, I want convert list<> to bytes so that send to my server and how to convert bytes to list<>
May you help me :)
Posted
Updated 18-Nov-10 22:33pm
v2

Hi Kid,

make sure the type in your generic list is serializable. Then do this:

List<yourtype> itemsToSerialize = new List<yourtype>();
itemsToSerialize.Add ( new yourtype() );
itemsToSerialize.Add ( new yourtype() );

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Create );
IFormatter formatter = new BinaryFormatter();
formatter.Serialize( stream, itemsToSerialize );

stream.Close();
</yourtype></yourtype>


This sample uses a file. But you can easyly adapt it to write to a socket instead. Here is the part that would deserialize List<yourtype> from a file:

Stream stream = new FileStream( @"MyApplicationData.dat", System.IO.FileMode.Open );

IFormatter formatter = new BinaryFormatter();
List<yourtyoe> itemsDeserialized = (List<yourtype>)formatter.Deserialize( stream );
stream.Close();
</yourtype></yourtyoe>


Again this will have to be adapted by you to utilize a socket instead.

Hope this helps!

Cheers

Manfred
 
Share this answer
 
Comments
kid218 19-Nov-10 4:48am    
Thank you for your help :)
Manfred Rudolf Bihy 19-Nov-10 10:26am    
You're welcome :)
It sounds like you want to use the BinaryFormatter class to serialize and deserialize your List<> into a MemoryStream that can be sent to your server: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter%28VS.71%29.aspx[^]

Also: You need to be sure that the object type the list contains is serializable (meaning they have the [SerializableAttribute()] applied to them).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900