StreamReader returning null

Viewed 572

My goal is to start using Stream in order to read a HTTP contents (HttpResponseMessage.Content). As for the moment I'm using ReadAsStringAsync to read the content, and I would like to improve the performance and memory usage with ReadAsStreamAsync.

In order to achieve that I've built a small unit test, which should arrange a Stream and then read it and convert it into the original object.

The expected result should be the original object after deserialize, but it returns null.

// Arrenge
List<TypiCode> typiCodes = new List<TypiCode>()
{
    new TypiCode()
    {
        Completed = true,
        Id = this._random.Next(1000),
        Title = Guid.NewGuid().ToString(),
        UserId = this._random.Next(1000)
    }
};

var jsonSerializer = new JsonSerializer();

Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();

// Act
List<TypiCode> result = null;
using (var streamReader = new StreamReader(stream))
{
    using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
    {                      
        result = jsonSerializer.Deserialize<List<TypiCode>>(jsonTextReader);
    }
}

//Assert
Assert.IsNotNull(result); --> Failed!

The model:

[Serializable]
public class TypiCode
{
    public int UserId { get; set; }
    public int Id { get; set; }
    public string Title { get; set; }
    public bool Completed { get; set; }
}

Why the StreamReader returning null?

1 Answers

After writing to the stream you are behind the data. You need to get to its start again.

Reset the streams position:

// your code

Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonSerializer.Serialize(jsonWriter, typiCodes);
jsonWriter.Flush();

stream.Seek(0, SeekOrigin.Begin);

// more of youre code

Doku:

Related