Problem in serializing
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.开发者_Python百科 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 ?
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;
}
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;
        }
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论