6

I have a Stream received from a PhotoResult of photoChooserTask_Completed(object sender, PhotoResult e) event handler.

The e.ChosenPhoto itself a Stream so I assign it to Stream stream. And I converted it to byte[] array using the method below:

    public static byte[] ReadImageFile2(Stream mystream)
    {
        // The mystream.length is still full here.
        byte[] imageData = null;
        using (BinaryReader br = new BinaryReader(mystream))
        {
            imageData = br.ReadBytes(Convert.ToInt32(mystream.Length));
        }
        // But imageData.length is 0
        return imageData;
    }

I don't know what is wrong with the BinaryReader, it returns imageData with just 0 length. Tried to cast type as br.ReadBytes((int)mystream.Length) but still doesn't work.

Also tried all of the answers in Creating a byte array from a stream but still not working. Maybe my e.ChosenPhoto cannot be used as a normal Stream.

Thank you.

Community
  • 1
  • 1
Tran Hoai Nam
  • 1,273
  • 2
  • 18
  • 35

1 Answers1

11

According to the docs, you may have to set the position of the stream to 0 before reading it:

using (BinaryReader br = new BinaryReader(mystream))
{
    mystream.Position = 0;
    imageData = br.ReadBytes(Convert.ToInt32(mystream.Length));
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165