im trying to convert a stream (System.Net.ConnectStream) to a byte array. Any thoughts/examples on how this can be done?
Asked
Active
Viewed 8,991 times
5
-
3Just read it into a buffer (`byte[]`). Look at [`Stream.Read`](http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx) on MSDN. – Oded Sep 28 '12 at 19:17
-
@Oded, yes, but it's not a very easy way to copy the whole content of the stream (unless you know its length, which isn't always the case with ConnectStream) – Thomas Levesque Sep 28 '12 at 19:19
3 Answers
14
Stream sourceStream = ... // the ConnectStream
byte[] array;
using (var ms = new MemoryStream())
{
sourceStream.CopyTo(ms);
array = ms.ToArray();
}

Thomas Levesque
- 286,951
- 70
- 623
- 758
-
In this case you use memory in 3 times more than your stream. It is not so good if your streams can take more memory than your pc have. In this case you need to use Stream.Read to read chunks of data from source stream and work with this chunks. – Kirill Bestemyanov Sep 28 '12 at 19:29
-
Note that `Stream.CopyTo` is only available in .NET 4.0 and up. See Kevin's answer for a pre 4.0 version. – Scott Chamberlain Sep 28 '12 at 20:30
4
Try this...
private static readonly object _lock = new object();
public static byte[] readFullStream(Stream st)
{
try
{
Monitor.Enter(_lock);
byte[] buffer = new byte[65536];
Int32 bytesRead;
MemoryStream ms = new MemoryStream();
bool finished = false;
while (!finished)
{
bytesRead = st.Read(buffer.Value, 0, buffer.Length);
if (bytesRead > 0)
{
ms.Write(buffer.Value, 0, bytesRead);
}
else
{
finished = true;
}
}
return ms.ToArray();
}
finally
{
Monitor.Exit(_lock);
}
}

Scott Chamberlain
- 124,994
- 33
- 282
- 431

Kevin
- 704
- 3
- 4
-
1Heres a tip, if you are using a rounded number buffer (like 64k in your example), you can replace `65536` with `64 << 10` where the left hand side is your number and on the right hand side `0 = Bytes, 10 = Kilobites, 20 = Megabytes, 30 = Gigabytes, ect...` So a 2MB buffer would be `2 << 20` – Scott Chamberlain Sep 28 '12 at 20:33
-
Also, why are you locking on _lock? if you are trying to get exclusive access to the stream you should be locking on something tied to the stream (or call [Stream.Synchronized](http://msdn.microsoft.com/en-us/library/system.io.stream.synchronized.aspx) before it gets passed in). You are doing nothing in your code that would break if you converted did two ***different*** streams at the same time – Scott Chamberlain Sep 28 '12 at 20:40
0
In one answer from Freeetje there is method writen named 'ReadToEnd'. Worked like a charm for me...
How do I get the filesize from the Microsoft.SharePoint.Client.File object?