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);
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();