Tag Archives: Visual Studio 2012

Read text from local files

When you have a text file added to your solution with, let’s say a list of words and you want to parse this in Windows Store applications, you can not do this in the conventional way anymore. But luckily, WinRT provides us with an API to get quick access to these files.

To access the words.txt file, we first need to add the namespace “using Windows.Storage;” to the top of our project.
Once we have done this, we can now access the API to load files that are stored within our application.
Make sure you have set the build action on the words.txt file to content, then, create a method to load the content from the file. Make sure that this method is async.

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
          

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/words.txt"));
            var lines = await FileIO.ReadLinesAsync(file);

            foreach (var word in lines)
            {
               var _x = new Windows.UI.Popups.MessageDialog(word);
               await _x.ShowAsync();
            }

        }

And there we go, a quick and easy way to read files from local content.