Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream.Length throws NotSupportedException

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?

like image 528
Nevin Mathai Avatar asked Jul 30 '10 16:07

Nevin Mathai


People also ask

How do you find the length of a stream?

Stream length is a dimensional property revealing the characteristic size of components of a drainage network and its contributing watershed surfaces (Strahler, 1964). It is obtained by dividing the total length of stream of an order by total number of segments in the order, Table 2.

What is a stream length?

The length of a stream is the distance measured along the stream channel from the source to a given point or to the outlet, a distance that may be measured on a map or from aerial photographs. On large-scale maps, it is measured along the geometrical axis, or the line of maximum depth.


2 Answers

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.

like image 87
Reed Copsey Avatar answered Oct 04 '22 01:10

Reed Copsey


This is what I do:

// Return the length of a stream that does not have a usable Length property public static long GetStreamLength(Stream stream) {     long originalPosition = 0;     long totalBytesRead = 0;      if (stream.CanSeek)     {         originalPosition = stream.Position;         stream.Position = 0;     }      try     {         byte[] readBuffer = new byte[4096];         int bytesRead;          while ((bytesRead = stream.Read(readBuffer, 0, 4096)) > 0)         {             totalBytesRead += bytesRead;         }      }     finally     {         if (stream.CanSeek)         {             stream.Position = originalPosition;         }     }      return totalBytesRead; } 
like image 26
Paul Bartlett Avatar answered Oct 04 '22 01:10

Paul Bartlett