TheFabledOne
TheFabledOne

Reputation: 238

Why is my file a different size after I upload it and convert to byte array?

I am using the following code to get a byte array out of an HttPostedFileBase object

byte[] mobileAppByteArray = default(byte[]);
using (MemoryStream ms = new MemoryStream())
{
  httpPostedFileObject.InputStream.CopyTo(ms);
  mobileAppByteArray = ms.GetBuffer();
}

The original size of the httpPostedFileObject is 3191KB, but after the above conversion and saving it to disk, the file size is 4096KB

I understand that the default buffer size for CopyTo is 4096, but even if I change the buffer size to 1024, the result is the same: file size is 4096KB.

How can I change my code so that my file remains as 3191KB after I save to disk?

Upvotes: 3

Views: 1064

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149108

That's because GetBuffer will return the entire underlying buffer, not just the portion of it that's been filled with bytes from the input stream. Try using the ToArray method instead:

mobileAppByteArray = ms.ToArray();

Upvotes: 5

Related Questions