How do I read a binary file in a Windows Store app?

允我心安 提交于 2020-01-11 09:08:09

问题


How can I read a binary file in a Windows Store app, or more specifically how can I create my Stream, when the System.IO namespace contains no File class?

The documentation examples for BinaryReader unhelpfully use File!


回答1:


You always access files in Windows Store apps using StorageFile class:

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);

You can then get the binary contents of the file using the WinRT APIs:

IBuffer buffer = await FileIO.ReadBufferAsync(file);
byte[] bytes = buffer.ToArray();

If you want to use BinaryReader you need a stream instead:

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("a");
Stream stream = (await file.OpenReadAsync()).AsStreamForRead();
BinaryReader reader = new BinaryReader(stream);

Make sure you only use ReadBytes() for binary data in this case which doesn't take encoding into account.



来源:https://stackoverflow.com/questions/13851462/how-do-i-read-a-binary-file-in-a-windows-store-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!