UWP: async read file into byte[]

testing picture testing · Mar 18, 2016 · Viewed 8.1k times · Source

I want to read a locally stored file into a byte array. How do I do that? This is my try:

StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(filePath);
var file = await folder.GetFileAsync(filePath);
var buffer = await FileIO.ReadBufferAsync(file);
DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer);
// doesn't work because ReadBytes wants a byte[] as parameter and also isn't asynchronous
byte[] result = dataReader.ReadBytes(buffer.Length);

Answer

Daniel Rosenberg picture Daniel Rosenberg · Jan 2, 2017

I think the other answers make things unnecessarily complicated. There is a convenient extension method IBuffer.ToArray() for this purpose.

Simply do this:

using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage;
...
IStorageFile file;
IBuffer buffer = await FileIO.ReadBufferAsync(file);
byte[] bytes = buffer.ToArray();