michielpost.nl

Reading and writing files in WinRT

10-07-2012

During the development of my first Windows 8 app, I searched for code examples on how to read and write files to the application storage.

I found a few examples, but they were all so complex.

Complex example of reading file data:
var inStream = readStream.GetInputStreamAt(0);
Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream);
await reader.LoadAsync((uint)readStream.Size);
string data = reader.ReadString((uint)readStream.Size);
reader.DetachStream();

This complex code is used in various open source libraries, like the WinRT XAML Toolkit http://winrtxamltoolkit.codeplex.com/
and Generic Object Storage project:
http://winrtstoragehelper.codeplex.com/
and the XAML Metro app storage helper:
http://metrostoragehelper.codeplex.com/

We don't need so many lines of code!

Today I finally found a really easy example that uses Windows.Storage.FileIO
var data = await FileIO.ReadTextAsync(file);

That was easy!

Jerry Nixon has a great overview on reading and writing files in WinRT on his blog:
http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html


 

Comments


No comments yet.

New Comment

Name
E-mail (not published)
Comment
Enter the code shown: