kazinix
kazinix

Reputation: 30153

StreamReader.ReadToEnd Not working in C#?

I'm trying to serialize an instance of the class Person:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;


[Serializable]
public class Person
{
    public string FirstName{ get; set; }
    public string MiddleName{ get; set; }
    public string LastName{ get; set; }
}

First, I serialized the object to JSON and write it on MemoryStream then convert it to string to display it on the page.

@using System.Runtime.Serialization.Json
@using System.Text


@{ Layout = null; 

    Person person = new Person();
    person.FirstName = "John";
    person.MiddleName = "Parker";
    person.LastName = "Santos";

    MemoryStream s = new MemoryStream();
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
    ser.WriteObject(s, person);
    string ss;

    using(StreamReader sr = new StreamReader(s, new UnicodeEncoding(), false))
    {
        ss = sr.ReadToEnd();
    }
}

@ss 

I expect the last line to print the JSON format of the object but it didn't. I suspect the StreamReader is not working since the the MemoryStream s has a length which I presume has the data already while ss has length of 0. What am I doing wrong?

Upvotes: 2

Views: 8135

Answers (1)

Polity
Polity

Reputation: 15130

You have to set the position of your memory stream back to the beginning before reading.

s.Position = 0;

Should fix your problem. See: http://msdn.microsoft.com/en-us/library/system.io.memorystream.position.aspx

Upvotes: 7

Related Questions