如何在C#中将Stream转换为byte []?[重复]

如何在C#中将Stream转换为byte []?[重复],第1张

如何在C#中将Stream转换为byte []?[重复]

调用下一个函数,例如

byte[] m_Bytes = StreamHelper.ReadToEnd (mystream);

功能:

public static byte[] ReadToEnd(System.IO.Stream stream)    {        long originalPosition = 0;        if(stream.CanSeek)        {  originalPosition = stream.Position;  stream.Position = 0;        }        try        { byte[] readBuffer = new byte[4096]; 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        { if(stream.CanSeek) {      stream.Position = originalPosition;  }        }    }


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5427605.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-11
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存