Reputation: 536
im trying to convert a stream (System.Net.ConnectStream) to a byte array. Any thoughts/examples on how this can be done?
Upvotes: 5
Views: 9199
Reputation: 430
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?
Upvotes: 0
Reputation: 704
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);
}
}
Upvotes: 4
Reputation: 292625
Stream sourceStream = ... // the ConnectStream
byte[] array;
using (var ms = new MemoryStream())
{
sourceStream.CopyTo(ms);
array = ms.ToArray();
}
Upvotes: 14