views:

63

answers:

4

I am getting a error when attempting stream.Length on a Stream object sent into my WCF method.

Unhandled Exception!
 Error ID: 0
 Error Code: Unknown
 Is Warning: False
 Type: System.NotSupportedException
 Stack:    at System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.get_Length()

How do you get the length of the stream? any examples?

A: 

You can't always get the length of a stream. In the case of a network stream, the only way of finding out the length is to read data from it until it's closed, for example.

What are you trying to do? Could you read from the stream until it's exhausted, copying the data into a MemoryStream as you go?

Jon Skeet
I just need the number of bytes to update a perf counter.
Nevin Mathai
@Nevin: What else is happening with the stream? Basically you won't be able to get at this information without changing the state by reading from it.
Jon Skeet
+2  A: 

Stream.Length only works on Stream implementations where seeking is available. You can usually check to see if Stream.CanSeek is true. Many streams, since they're being streamed, are of a nature where it's impossible to know the length in advance.

If you must know the length, you may need to actually buffer the entire stream, loading it into memory in advance.

Reed Copsey
+1  A: 

It is not always possible to get the length of a stream if it doesn't support seeking. See the exception table on the Stream class.

For example, a stream hooked up to another process (network stream, standard output, etc) can produce any amount of output, depending on how the other process is written, and there's no way for the framework to figure out how much data there is.

In the general case, you just have to read in all of the data until the end of the stream and then figure out how much you've read.

dsolimano
A: 

TcpClient.EndRead() should return the number of bytes that are in the stream.

--Edit, of course you need to be using a TCP Stream