-1

How can I Convert the Ilist< stream> into Byte[]? I tried the codes below but I'm getting null value.

  byte[] buffer = new byte[16*1024];
         using (MemoryStream ms = new MemoryStream())
         {
             int read;
             while ((read = m_streams[0].Read(buffer, 0, buffer.Length)) > 0)
             {
                 ms.Write(buffer, 0, read);
             }
             return ms.ToArray();
         }
Vic
  • 457
  • 1
  • 6
  • 23
  • How this code can return "null value" ever is beyond me... You at least should have copied [second answer](https://stackoverflow.com/a/6586039/477420) instead of the first one... – Alexei Levenkov Feb 01 '18 at 04:28

1 Answers1

4

Pretty easy with LINQ and SelectMany, which will concatenate the byte arrays for you.

Be sure to dispose your streams when you're done with them.

//using System.Linq;

byte[] results = m_streams.SelectMany(s =>
{
    var buffer = new byte[s.Length];
    s.Read(buffer, 0, (int)s.Length);
    return buffer;
}).ToArray(); 
rokkerboci
  • 1,167
  • 1
  • 7
  • 14
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Ok thanks it worked. I update the code because I'm getting error. – Vic Feb 01 '18 at 03:40
  • Since request in question is very strange by itself it does not really matter how inefficient solution is... But for somewhat practical usage on reasonably sized files consider not to grow resulting array dynamically but at least compute size and allocate once... – Alexei Levenkov Feb 01 '18 at 04:26
  • @AlexeiLevenkov C# arrays don't grow dynamically so I am not sure what you're referring to specifically. This solution doesn't contain any ArrayList or List objects, just arrays and enumerators. P.S. I am not sure these are files; they are just memory streams with unknown specifics. – John Wu Feb 01 '18 at 04:49
  • @JohnWu solution uses `ToArray`. It had to allocate buffers as it constructing the final array... And before probably 4.7.x it would copy data on each allocation (latest one uses fancy https://github.com/dotnet/corefx/blob/master/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs that avoid extra copies when growing the inner array which was there all the time before that to my knowledge) – Alexei Levenkov Feb 01 '18 at 15:10
  • Oh I see. You're concerned about using `ToArray()` on an enumerator over a large set, inside the .NET framework. Sure, I think you could improve on the performance with a single large array and windowed reads, without much difficulty, although I wouldn't necessarily assign that to an intern to be coded. – John Wu Feb 01 '18 at 16:41