我试图将流(System.Net.ConnectStream)转换为字节数组。关于如何做到这一点的任何想法/例子?
问问题
8577 次
3 回答
14
Stream sourceStream = ... // the ConnectStream
byte[] array;
using (var ms = new MemoryStream())
{
sourceStream.CopyTo(ms);
array = ms.ToArray();
}
于 2012-09-28T19:18:56.780 回答
4
试试这个...
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);
}
}
于 2012-09-28T20:25:27.170 回答
0
在 Freeetje 的一个答案中,有一种名为“ReadToEnd”的方法。对我来说就像一个魅力......
于 2014-10-02T16:53:12.800 回答