在.NET中将流(未知长度)转换为字节数组的最佳方法?

发布于 2024-09-06 12:11:19 字数 584 浏览 8 评论 0原文

我有以下代码来从流(在本例中是从命名管道)读取数据并将数据读取到字节数组中:

// 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

木有鱼丸 2024-09-13 12:11:19

无耻地复制了 Jon Skeet 的文章

public static byte[] ReadFully (Stream stream)
{
   byte[] buffer = new byte[32768];
   using (MemoryStream ms = new MemoryStream())
   {
       while (true)
       {
           int read = stream.Read (buffer, 0, buffer.Length);
           if (read <= 0)
               return ms.ToArray();
           ms.Write (buffer, 0, read);
       }
   }
}

Shamelessly copied from Jon Skeet's article.

public static byte[] ReadFully (Stream stream)
{
   byte[] buffer = new byte[32768];
   using (MemoryStream ms = new MemoryStream())
   {
       while (true)
       {
           int read = stream.Read (buffer, 0, buffer.Length);
           if (read <= 0)
               return ms.ToArray();
           ms.Write (buffer, 0, read);
       }
   }
}
那些过往 2024-09-13 12:11:19
int read = stream.Read (buffer, 0, buffer.Length);

如果没有可用数据,该行将永远阻塞。 Read 是一个阻塞函数,它将阻塞线程直到读取至少一个字节,但如果没有数据,它将永远阻塞。

int read = stream.Read (buffer, 0, buffer.Length);

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.

百思不得你姐 2024-09-13 12:11:19

看来您当前的解决方案非常好。如果您希望代码看起来更干净,您可以考虑将其包装到扩展方法中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文