How to read file (Metro/WinRT)

20,595

Solution 1

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;
}

Solution 2

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()

Solution 3

You can get your file by using this:

StorageFile file3 = await StorageFile.GetFileFromPathAsync(@"C:\myFile.txt");
Share:
20,595
annonymously
Author by

annonymously

I could be over 50 years old, or I couldn't. I could be 3 feet tall, or I couldn't. I could eat raw coffee beans, or I couldn't. I could have a pet elephant, and you wouldn't know it. That is the nature of annonimity. Spelled with double 'n' first instead of second. Yeah.

Updated on July 05, 2022

Comments

  • annonymously
    annonymously almost 2 years

    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
    annonymously over 11 years
    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.
  • Matthew Watson
    Matthew Watson over 11 years
    I would, but bizarrely, the code is in a bitmap rather than selectable text. :(
  • Firanto
    Firanto over 9 years
    This is a great help. I've been stumble for couple of days looking for this. Thanks.