Thursday, June 28, 2012

Reading file content using DataReader.ReadBytes in Metro apps

The Windows.Storage.Streams.DataReader.ReadBytes method stupidly breaks with the convention of the other methods on the DataReader object, by requiring you to pass in a variable to populate, instead of instantiating a new variable and returning it.

Looking at the declaration of this method:

[MethodImpl]
void IDataReader.ReadBytes([Out] byte[] value);

we see that the value is marked with an Out attribute. Note that this is not the same as an out parameter modifier.

To have your passed in value correctly populated, you need to instantiate the byte array to pass in, using the correct capacity. The capacity is available on your reader in the UnconsumedBufferLength property.

Here's a sample of using this method:

StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("[filename]");
IBuffer buffer = await FileIO.ReadBufferAsync(file);
DataReader reader = DataReader.FromBuffer(buffer);
byte[] fileContent = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(fileContent);

2 comments:

  1. Thank you. I just shouted at Microsoft on their reference page about the lack of an example of this. I was missing the new.. of course

    ReplyDelete