How to calculate the size of the file before saving it to the disk from the stream?

.net, c#

Solution

If you have a `Stream` object, you can use its `Length` property - which gives the length in bytes - but not all streams support it (for example, memory and file stream do, but network streams generally don't).

If you're starting from a byte array (`byte[]`) use its `Length` property to get the amount of bytes.

If you're using a string, it depends on the encoding. For example, for UTF8, you can use

int byteCount = System.Text.Encoding.UTF8.GetByteCount(str);

Problem

I have a scenario where i have to disallow the user to save the file only if the size of the directory reaches the specified limit. The file would be created from the stream. How to get the file size(approximate) before saving the stream to disk ? (Note : User will not provide the any file or file path. I would get data in the form of byte[] or strings.)

Original source