How do I open an embedded text file in WinRT?

221 views Asked by At

I have an embedded text file in my Windows 8 Store App and I have it currently set to content for build actions. I tried using this following code (works on Windows Phone) and I have modified it a bit based on the instructions from this post:

Read a Text File in Windows 8

But it seems a lot of the syntax has changed and most tutorials I can find online focus on what was available in the Windows 8 Consumer Preview and not the final release of Windows 8. This is the code I'm currently using, some of the original syntax from the Windows Phone version still exists:

    private async void Search(object sender, RoutedEventArgs e)
    {
        var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"folder\data.txt");
        var stream = await file.OpenStreamForReadAsync();
        var rdr = new StreamReader(stream.AsInputStream());


        try
        {
            while ((line = file.ReadLine()) != null)
            {
                string[] temp = line.Split(':');
                int tmp = 0;

                int.TryParse(temp[0], out tmp);

                data.Add(tmp, temp[1]);
            }
        }
        finally
        {
            if (file != null)
                file.Close();
        }
    }
3

There are 3 answers

0
Jonathan ANTOINE On BEST ANSWER

The easiest and quickest way would be to use the FileIO helper this way :

// custom app package uri
var uri = new Uri("ms-appx:///folder/data.txt");

//get the file
var localFile = await StorageFile.GetFileFromApplicationUriAsync(uri);

// read the text
var text = await Windows.Storage.FileIO.ReadTextAsync(localFile);
0
Oscar Wahltinez On
0
Scott Dorman On

First, verify that that file is marked a content and that "Copy if newer" is set to true.

Your method should look something like this:

private async void Search(object sender, RoutedEventArgs e)
{
    var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"folder\data.txt");
    var stream = await file.OpenStreamForReadAsync();
    var rdr = new StreamReader(stream.AsInputStream());
    var contents = await rdr.ReadToEndAsync();
}

This will read the contents of your file into a string variable name contents. From there, you can do whatever you need to with it.

The file access APIs in WindowsRT come from the ".NET for Windows Store apps" profile, so when you're looking on MSDN you need to make sure that the APIs you want to use include that in the list of supported frameworks.