Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.)

like image 482
Prashanth R Avatar asked Jan 22 '26 22:01

Prashanth R


2 Answers

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);
like image 117
Eli Arbel Avatar answered Jan 25 '26 11:01

Eli Arbel


If you're using a MemoryStream you could do something like this

byte[] fileData = stream.ToArray();
var fileSize = fileData.Length;
like image 33
Erik Karlstrand Avatar answered Jan 25 '26 13:01

Erik Karlstrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!