How to convert a file into byte array in memory?
As opposed to saving the data as a string (which allocates more memory than needed and might not work if the binary data has null bytes in it), I would recommend an approach more like
foreach (var file in files)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
string s = Convert.ToBase64String(fileBytes);
// act on the Base64 data
}
}
}
Also, for the benefit of others, the source code for IFormFile
can be found on GitHub
You can just write a simple extension:
public static class FormFileExtensions
{
public static async Task<byte[]> GetBytes(this IFormFile formFile)
{
using (var memoryStream = new MemoryStream())
{
await formFile.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}
}
Usage
var bytes = await formFile.GetBytes();
var hexString = Convert.ToBase64String(bytes);