Search code examples
c#windows-8winrt-async

How do I open an embedded text file in WinRT?


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

Solution

  • 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);