1

I am looking for a solution in C# language which can convert System.IO.Stream to byte[]. I have tried the below code but i am receiving byte[] as null. Can some one guide what i am missing from below code ? I am receiving from Alfresco Web service, no way i can read the file unless saving in to temp location.

 private static byte[] ReadFile(Stream fileStream)
    {
        byte[] bytes = new byte[fileStream.Length];

        fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length));
        fileStream.Close();

        return bytes;

        //using (MemoryStream ms = new MemoryStream())
        //{
        //    int read;
        //    while ((read = fileStream.Read(bytes, 0, bytes.Length)) > 0)
        //    {
        //        fileStream.CopyTo(ms);
        //    }
        //    return ms.ToArray();
        //}
    }
2
  • 2
    Check this: stackoverflow.com/questions/221925/… Commented Jul 5, 2017 at 14:23
  • a stream can be huge (larger than the allowed array size), or even infinite in size; in the general sense, this is just not a good idea! Commented Jul 5, 2017 at 14:31

1 Answer 1

6

Once I made an extension method for it:

public static byte[] ToArray(this Stream s)
{
    if (s == null)
        throw new ArgumentNullException(nameof(s));
    if (!s.CanRead)
        throw new ArgumentException("Stream cannot be read");

    MemoryStream ms = s as MemoryStream;
    if (ms != null)
        return ms.ToArray();

    long pos = s.CanSeek ? s.Position : 0L;
    if (pos != 0L)
        s.Seek(0, SeekOrigin.Begin);

    byte[] result = new byte[s.Length];
    s.Read(result, 0, result.Length);
    if (s.CanSeek)
        s.Seek(pos, SeekOrigin.Begin);
    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

note that even querying .Position can fail - that isn't supported on all streams

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.