Skip to main content

Reading a StorageFile to a byte array in C#

Reading a StorageFile to a byte[] or an IRandomAccessStream in a Windows 8 app wasn't exactly obvious and the examples I found included other classes or unnecessary processing. I created this solution based upon what I learned and wanted to share it...

  1.         /// <summary>
  2.         /// Loads the byte data from a StorageFile
  3.         /// </summary>
  4.         /// <param name="file">The file to read</param>
  5.         public async Task<byte[]> ReadFile(StorageFile file)
  6.         {
  7.             byte[] fileBytes = null;
  8.             using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
  9.             {
  10.                 fileBytes = new byte[stream.Size];
  11.                 using (DataReader reader = new DataReader(stream))
  12.                 {
  13.                     await reader.LoadAsync((uint)stream.Size);
  14.                     reader.ReadBytes(fileBytes);
  15.                 }
  16.             }
  17.  
  18.             return fileBytes;
  19.         }