在.NET中将流(未知长度)转换为字节数组的最佳方法?
我有以下代码来从流(在本例中是从命名管道)读取数据并将数据读取到字节数组中:
// NPSS is an instance of NamedPipeServerStream
int BytesRead;
byte[] StreamBuffer = new byte[BUFFER_SIZE]; // size defined elsewhere (less than total possible message size, though)
MemoryStream MessageStream = new MemoryStream();
do
{
BytesRead = NPSS.Read(StreamBuffer, 0, StreamBuffer.Length);
MessageStream.Write(StreamBuffer, 0, BytesRead);
} while (!NPSS.IsMessageComplete);
byte[] Message = MessageStream.ToArray(); // final data
您能否看一下并让我知道是否可以更有效或更整洁地完成此操作?使用 MemoryStream 看起来有点混乱。谢谢!
I have the following code to read data from a Stream (in this case, from a named pipe) and into a byte array:
// NPSS is an instance of NamedPipeServerStream
int BytesRead;
byte[] StreamBuffer = new byte[BUFFER_SIZE]; // size defined elsewhere (less than total possible message size, though)
MemoryStream MessageStream = new MemoryStream();
do
{
BytesRead = NPSS.Read(StreamBuffer, 0, StreamBuffer.Length);
MessageStream.Write(StreamBuffer, 0, BytesRead);
} while (!NPSS.IsMessageComplete);
byte[] Message = MessageStream.ToArray(); // final data
Could you please take a look and let me know if it can be done more efficiently or neatly? Seems a bit messy as it is, using a MemoryStream. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无耻地复制了 Jon Skeet 的文章。
Shamelessly copied from Jon Skeet's article.
如果没有可用数据,该行将永远阻塞。 Read 是一个阻塞函数,它将阻塞线程直到读取至少一个字节,但如果没有数据,它将永远阻塞。
This line will block forever if there is no data Available. Read is a blocking function and it will block the thread until it reads at least one byte but if there is no data then it will block forever.
看来您当前的解决方案非常好。如果您希望代码看起来更干净,您可以考虑将其包装到扩展方法中。
It looks like your current solution is pretty good. You may consider wrapping it up into an extension method if you'd like the code to look cleaner.