Stream.Length throws NotSupportedException

Nevin Mathai picture Nevin Mathai · Jul 30, 2010 · Viewed 49.9k times · Source

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?

Answer

Reed Copsey picture Reed Copsey · Jul 30, 2010

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.