I encountered this same problem when using WCF services. I needed to get the contents of a POST message, and was using a Stream
argument in my method to get the contents of the message's body. Once I got the stream, I wanted to read its contents all at once, and needed to know what size byte array I would need. So, in the allocation of the array, I would call System.IO.Stream.Length
and get the exception mentioned by the OP. Is the reason you need to know the length of the stream so that you can read the contents of the entire stream?
You can actually read the entire contents of the stream into a string using System.IO.StreamReader
. If you still need to know the size of your stream, you can get the length of the resulting string. Here's the code for how I solved this problem:
[OperationContract]
[WebInvoke(UriTemplate = "authorization")]
public Stream authorization(Stream body)
{
// Obtain the token from the body
StreamReader bodyReader = new StreamReader(body);
string bodyString = bodyReader.ReadToEnd();
int length = bodyString.Length; // (If you still need this.)
// Do whatever you want to do with the body contents here.
}