im trying to convert a stream (System.Net.ConnectStream) to a byte array. Any thoughts/examples on how this can be done?
3 Answers
Stream sourceStream = ... // the ConnectStream
byte[] array;
using (var ms = new MemoryStream())
{
sourceStream.CopyTo(ms);
array = ms.ToArray();
}
2 Comments
Kirill Bestemyanov
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.
Scott Chamberlain
Note that
Stream.CopyTo is only available in .NET 4.0 and up. See Kevin's answer for a pre 4.0 version.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);
}
}
2 Comments
Scott Chamberlain
Heres 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 << 20Scott Chamberlain
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 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
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?
byte[]). Look atStream.Readon MSDN.