tags:

views:

70

answers:

2

Hello Guyz,

Presently I need to serialize one of my object which contains more my own classes object. But the problem is I dont want to save it in a file and then retrieve it into memory stream. Is there any way to directly serialize my object into stream.

I used BinaryFormatter for seializing. First I used a MemoryStream directly to take serialize output but it is giving error at time of deserialization. But later when I serialize it with a file then close it and again reopen it , it works perfectly. But I want to take it direct into stream because in my program I need to do it frequently to pass it into network client. And using file repeatedly might slow down my software.

Hope I clear my problem. Any Sugetion ?

+4  A: 

If you're trying to deserialize from the same MemoryStream, have you remembered to seek back to the beginning of the stream first?

var foo = "foo";
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
    // Serialize.
    formatter.Serialize(stream, foo);

    // Deserialize.
    stream.Seek(0, SeekOrigin.Begin);
    foo = formatter.Deserialize(stream) as string;
}
Will Vousden
YOu know I am a very stupid person, How I did forget that.Thanks man.Sorry for bothering you all for this.
Harun
+1 for specifically mentioning the seek which seems like the OP's problem.
Sam
@Harun, if this answer correctly addressed your problem click on the check mark under the number to mark it as the correct answer. This gives the poster rep points for the answer and helps your own "% accepted" score which encourages people to answer your questions.
Sam
+1  A: 

Here's a quick and dirty sample, of serializing back and forth a string. Is this what your trying to do?

static void Main(string[] args)
        {
            var str = "Hello World";

            var stream = Serialize(str);
            stream.Position = 0;
            var str2 = DeSerialize(stream);

            Console.WriteLine(str2);
            Console.ReadLine();
        }

        public static object DeSerialize(MemoryStream stream)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(stream);
        }
        public static MemoryStream Serialize(object data)
        {

            MemoryStream streamMemory = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(streamMemory, data);

            return streamMemory;

        }
JoshBerke