首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取传入HttpListenerRequest输入流的内容长度

获取传入HttpListenerRequest输入流的内容长度
EN

Stack Overflow用户
提问于 2022-07-01 20:50:47
回答 1查看 64关注 0票数 0

我正在使用C#的HttpListner制作服务器,服务器正在处理来自传入post请求的二进制数据。我正在尝试创建post请求处理程序,而且由于我正在处理二进制数据,所以我使用的是byte[] (这是我正在读取的缓冲区)。但问题是,在向缓冲区读取任何内容之前,我必须提供缓冲区的长度。我尝试了HttpListnerRequest.InputStream.Length,但它抛出了如下内容:

代码语言:javascript
复制
System.NotSupportedException: This stream does not support seek operations.

还有别的方法可以得到溪流的长度吗?其他类似问题的答案只使用StreamReader,但StreamReader不执行二进制操作。

下面是抛出错误的代码。

代码语言:javascript
复制
// If the request is a post request and the request has a body
Stream input = request.InputStream; // "request" in this case is the HttpListnerRequest
byte[] buffer = new byte[input.Length]; // Throws System.NotSupportedException.
input.Read(buffer, 0, input.Length);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-01 20:50:47

您可以使用HttpListnerRequest.ContentLength64,它表示请求体的长度,在本例中是输入流。示例:

代码语言:javascript
复制
// If the request is a post request and the request has a body
long longLength = request.ContentLength64;
int length = (int) longLength;
Stream input = request.InputStream; // "request" in this case is the HttpListnerRequest
byte[] buffer = new byte[length];
input.Read(buffer, 0, length);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72834510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档