Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file (Metro/WinRT)

I'm quite astounded by the apparent complexity of this seemingly simple task. I know that I have to use the StorageFile class, and I've found this example, but I just want to read one single file, to which I know the path, and read it's data as text into a string.

From what I've been able to gather, to read a file with StorageFile, I have to go through a bunch of interfaces; IAsyncOperation<StorageFile> and IAsyncOperationCompletedHandler.

There must be a better (simpler) way. Something like:

using (StorageFile sf = StorageFile.OpenAsync("myFile.txt"))
{
    string line = sf.ReadLine();
}

Obviously this doesn't work, but maybe I've missed something, or someone could explain to me how to read a file in a different way?

like image 762
annonymously Avatar asked Oct 03 '12 07:10

annonymously


2 Answers

This web page might be helpful: http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html

Relevant code:

public string CurrentFileBuffer
{
    get; private set;
}

public async void ReadTextFile(string Path)
{
    var folder = Package.Current.InstalledLocation;
    var file = await folder.GetFileAsync(Path);
    var read = await FileIO.ReadTextAsync(file);
    CurrentFileBuffer = read;
}
like image 98
Matthew Watson Avatar answered Sep 18 '22 15:09

Matthew Watson


Windows.Storage.FileIO has a bunch of helper/utility methods that do the job in a single line of code rather than using StorageIO interfaces and classes.

e.g.

ReadLineAsync()
ReadTextAsync()
WriteLineAsync()
WriteTextAsync()
like image 21
Dangling Neuron Avatar answered Sep 19 '22 15:09

Dangling Neuron