Search code examples
c#asp.nethttppostedfilebase

HttpPostedFileBase loses ContentLength


I've got a function that accepts two HttpPostedFileBase parameters. As soon as the function begins, I convert to a byte array (as seen below).

Before converting to the byte array I can breakpoint the function and see that the ContentLength property has a value (something like 1123512), but sometimes one of the byte arrays is set to 0, and when I inspect the HttpPostedFileBase again, ContentLength is set to 0?

public static async Task FileCheck(HttpPostedFileBase Image1, HttpPostedFileBase Image2)
{
    byte[] ByteArray1 = HttpPostedFileBaseToBase64ByteArray(Image1);
    byte[] ByteArray2 = HttpPostedFileBaseToBase64ByteArray(Image2);
}

Here is the byte array conversion:

public static byte[] HttpPostedFileBaseToBase64ByteArray(HttpPostedFileBase Image)
{
    //Get bytes from image
    byte[] ImageAsBytes = new byte[Image.ContentLength];

    //Read image binary
    using (BinaryReader BinaryReader = new BinaryReader(Image.InputStream))
    {
        //Insert into byte array
        ImageAsBytes = BinaryReader.ReadBytes(Image.ContentLength);
    }

    return ImageAsBytes;
}

Like I said, this only occurs sometimes which is strange.


Solution

  • Using VDWWD's answer of Image.InputStream.Position = 0; seemed to fix this.