Search code examples
c#stream.net-3.5filesizememorystream

How can i get length (file size) of a task stream


My primary requirement is to get length (File Size) of a task stream System.Threading.Tasks.Task<System.IO.Stream>. In a memorystream i used to get the file size using "stream.Result.Length" but when i tried to use the same in a taskstream it throws an exception saying System.NotSupportedException, Seems like the stream doesn't support that property. I think there is a difference between memory streams and other streams.

Exception occurred handling notification:System.NotSupportedException: This stream does not support seek operations.

Could you please give me any instructions how can i achieve this i found this link which gives me the instructions. I am using .Net 3.5 therefore i cant use ConvertTo() functions that is there in .Net 4


Solution

  • The point of a stream is that you don't need to have all the data available before you can start processing the first part of it. MemoryStream is an exception, in that it does have the entire contents of the stream in memory at the same time, so it can "support seek operations" to tell you things like how big the stream is.

    If you need the full size of a stream that can't seek, you're going to have to consume the entire stream to find that out. If the stream is always going to be relatively small, you could copy its contents into a MemoryStream. If it's going to be larger, you could copy its contents into a file on disk.

    You may want to examine why you need to know the length. If it's so that you can cancel uploads that are too large, for example, then perhaps you should just start processing the upload in chunks, but after each piece of data comes in check how much data you've received so far, and cancel the process if it gets too big.