Convert HttpContent into byte[]

Deadly 提交于 2019-12-05 03:35:05

HttpContent has a Async method which return ByteArray i.e (Task of ByteArray)

 Byte[] byteArray = await Content.ReadAsByteArrayAsync();

You can run the method synchronously

Byte[] byteArray = Content.ReadAsByteArrayAsync().Result;
if (!content.IsMimeMultipartContent())
{
    throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported");
}

var uploadPath = **whatever**;
if (!Directory.Exists(uploadPath))
{
    Directory.CreateDirectory(uploadPath);
}

var provider = new MultipartFormDataStreamProvider(uploadPath);
await content.ReadAsMultipartAsync(provider);

return File.ReadAllBytes(provider.FileData[0].LocalFileName);

Please look at CopyToAsync(Stream, TransportContext) method exposed by ByteArrayContent Class. [msdn link]

You can use HttpContent.ReadAsByteArrayAsync:

byte[] bytes = await response.Content.ReadAsByteArrayAsync();

Or, you can read the content with HttpContent.ReadAsStreamAsync and extract to a byte[] from there:

var stream = response.Content.ReadAsStreamAsync();
using (var memoryStream = new MemoryStream())
{
      await stream.CopyToAsync(stream);
      return memoryStream.ToArray();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!