15

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?

annonymously
  • 4,708
  • 6
  • 33
  • 47
  • I think the "Windows-8" and "Microsoft-metro" and "Winrt" tags are too subtle. ;) Might want to edit your question to say NOTE: THIS IS FOR WINDOWS METRO! – Matthew Watson Oct 03 '12 at 07:57
  • @Matthew Watson Yeah, thanks. I should probably have realized there would be an immediate rush to get reputation with a title like that. :) – annonymously Oct 03 '12 at 07:59

4 Answers4

30

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;
}
annonymously
  • 4,708
  • 6
  • 33
  • 47
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Thanks, finally someone actually read my question. This was giving me a really hard time. If you'd be so inclined, you could copy some of the code from that link to help future visitors. – annonymously Oct 03 '12 at 08:17
  • I would, but bizarrely, the code is in a bitmap rather than selectable text. :( – Matthew Watson Oct 03 '12 at 09:07
  • This is a great help. I've been stumble for couple of days looking for this. Thanks. – Firanto Oct 13 '14 at 10:24
5

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()
Dangling Neuron
  • 231
  • 1
  • 4
4

You can get your file by using this:

StorageFile file3 = await StorageFile.GetFileFromPathAsync(@"C:\myFile.txt");
Manuel
  • 3,828
  • 6
  • 33
  • 48
0

You can use the FileIO class like so.

public async void Read(IStorageFile file)
{
    var lines = await FileIO.ReadLinesAsync(file);

}
vidstige
  • 12,492
  • 9
  • 66
  • 110