1.Convert Byte[] to Stream:
Stream s = new MemoryStream(byteArray);2.Convert Stream to Bytep[]:
byte[] m_Bytes = ReadToEnd(myStream);
Public static byte[] readToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096]; //最大Size
int totalBytesRead = 0;
int bytesRead;
while((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length-totalBytesRead))>0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
本文介绍如何将字节数组转换为内存流,以及如何从流中读取所有字节到字节数组的方法。通过示例代码详细展示了使用C#实现这两种转换的具体步骤。

3490

被折叠的 条评论
为什么被折叠?



