I am making a server using C#'s HttpListner
, and the server is handling incoming binary data from incoming post requests. I am trying to make the post request handler, and because I am handling binary data I am using byte[]
(which is the buffer I am reading to). But the issue is I have to supply the length of the buffer before reading anything to the buffer. I tried HttpListnerRequest.InputStream.Length
, but it throws this:
System.NotSupportedException: This stream does not support seek operations.
Is there another way to get the length of the stream? Other answers to similar questions just use StreamReader
, but StreamReader does not do binary.
Here is my code that throws the error.
// 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);
CodePudding user response:
You can use HttpListnerRequest.ContentLength64
, which represents the length of the request body, which in this case is the input stream. Example:
// 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);