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();
        //}
    }
Dinesh
  • 41
  • 1
  • 2
  • 9
  • 2
    Check this: https://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream – Dave Becker Jul 05 '17 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! – Marc Gravell Jul 05 '17 at 14:31

1 Answers1

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;
}
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65