1

I receive IFormFile and I would like to convert it to byte[], my code looks like this:

private ProductDto GenerateData(Request product, IFormFile file)
{
    if (file != null)
    { 
        using (var item = new MemoryStream())
        {
            file.CopyTo(item);
            item.ToArray();
        }
    }

    return new ProductDto
    {
        product_resp = JsonConvert.SerializeObject(product).ToString(),
        file_data = item; // I need here byte [] 
    };
}

I've tried something but I'm not even sure if I can convert IFormFile to byte[] on way I tried, not sure if it's right approach.

Anyway, thanks for any help.

demo
  • 5,676
  • 16
  • 65
  • 141
Roxy'Pro
  • 3,742
  • 6
  • 36
  • 82
  • 1
    Does this answer your question? [How to convert a file into byte array in memory?](https://stackoverflow.com/questions/36432028/how-to-convert-a-file-into-byte-array-in-memory) – demo Nov 15 '19 at 15:02
  • Hi @Roxy'Pro Did you solve the problem or not? – Robert N. Dean Nov 20 '19 at 19:11

1 Answers1

2

I have an extension for it:

public static byte[] ToByteArray(this Stream input)
{
        byte[] buffer = new byte[16 * 1024];
        using (var ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
}

then

  if (file != null)
  { 
        using (var stream = file.OpenReadStream())
        {
            return new ProductDto
            {
                product_resp = JsonConvert.SerializeObject(product).ToString(),
                file_data = stream.ToByteArray()
            };
        }
    }
Roman Marusyk
  • 21,493
  • 24
  • 66
  • 105
  • 1
    Why not use `input.CopyTo(ms);` instead, or if you really want to enforce a 16k buffer, then `input.CopyTo(ms, 16 * 1024);`? – Robert McKee Nov 15 '19 at 15:10
  • make sense, but result will be the same – Roman Marusyk Nov 15 '19 at 15:15
  • 1
    Thanks for your previous comment which linked to similar discussion. `.CopyTo` wasn't available in .NET before 4.0, so if you need to support .NET prior to that you had to do the above instead. – Robert McKee Nov 15 '19 at 15:16