Read and Write Text Files (Windows 8.1 / Phone 8.1 Universal Apps)

Here is a simple way to read and write text files in a Windows app. Text-based files can be really useful, and you can even encode XML, JSON, and similar data into a text file.

This technique will work in any Windows 8.1 Store, Windows Phone 8.1, or Windows 8.1 Universal app (for a Universal app, put the code in a class in the shared project so the code can be accessed in both Windows and Windows Phone versions of the app).

Namespaces

Firstly, add these namespaces to your class:

using System.Threading.Tasks;
using Windows.Storage;
using System.IO;

Then add the following two methods. I’ve included comments to explain what each line does.

Write text to a file

This method receives a filename and some text content, and writes the content to a file (with the given filename, natch) into local storage:

async Task saveStringToLocalFile(string filename, string content)
{
    // saves the string 'content' to a file 'filename' in the app's local storage folder
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(content.ToCharArray());

    // create a file with the given filename in the local folder; replace any existing file with the same name
    StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

    // write the char array created from the content string into the file
    using (var stream = await file.OpenStreamForWriteAsync())
    {
        stream.Write(fileBytes, 0, fileBytes.Length);
    }
}

Reading text from a file

Now that we can write text to a file we need a way to read it back. This method takes a filename and reads the text in that file and returns it as a string:

public static async Task<string> readStringFromLocalFile(string filename)
{
    // reads the contents of file 'filename' in the app's local storage folder and returns it as a string

    // access the local folder
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    // open the file 'filename' for reading
    Stream stream = await local.OpenStreamForReadAsync(filename);
    string text;

    // copy the file contents into the string 'text'
    using (StreamReader reader = new StreamReader(stream))
    {
        text = reader.ReadToEnd();
    }            
          
    return text;
}

What next?

That’s it. Use the two methods above to read and write text to a file. You can use these methods in conjunction with parsing algorithms to read and write XML, JSON, etc., or to simply save settings and data for your app.

If you want to test that it’s working correctly, you could write a file and then read back the same file.

Make your Windows Phone 8.1 App a Share Target (C# or Visual Basic)

On mobile platforms, where it’s important to move between apps fluidly with somewhat limiting interfaces and partitioned app model, sharing content between apps is very powerful.

Windows Phone’s sharing implementation is great, and you can make your app a share target (allow it to receive content sent from another app) with just a few lines of code. 

In this article I’ll demonstrate how to make a very simple app that is a share target for a hyperlink. The app will display the link it receives in a popup box, and then return the user back to the app that shared the link.

Note: this method targets Windows Phone 8.1.

This simple implementation breaks down into two steps:

  • Step 1: Enable share target permission
  • Step 2: Add the code to receive shared content

Get started 

Create a new project for Windows Phone. You can use either C# or Visual Basic to follow along. Visual Studio 2013 (or the Express equivalent) is required. 

Step 1: Give your App Share Target Permission 

A Windows Phone app must declare it is a share target, and what content it can receive from shares. This is what determines that your app should pop up in the list of targets when a user shares content from another app. 

Open Package.appxmanifest and select the Declarations tab, then: 

  1. In the Available Declarations panel on the left, select Share Target from the drop-down 
  2. Click Add 
  3. In the Share Description field enter a name/description (e.g. Media Link
  4. Type the content type to receive in the Data format: field. In this example use URI (a hyperlink, such as you would share from Internet Explorer). 


Now your app is able to receive shared content from another app. 

Step 2: Implement the Code 

Add the following method to App.Xaml.cs / App.Xaml.vb. The OnShareTargetActivated method will run whenever you app is launched. 

You need first add some using declarations at the top of the class:

C#

using Windows.UI.Popups;
using Windows.ApplicationModel.Activation;

 VB

Imports Windows.UI.Popups
Imports Windows.ApplicationModel.Activation

Next, add in the method that runs when the user chooses the app when sharing:

C#

protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    var link = args.ShareOperation.Data.GetWebLinkAsync().GetResults();
    MessageDialog messageDialog = new MessageDialog(link.ToString());
    messageDialog.ShowAsync();
    args.ShareOperation.ReportCompleted();
}

VB

protected Overrides Sub OnShareTargetActivated(args As ShareTargetActivatedEventArgs)
    Dim link = args.ShareOperation.Data.GetWebLinkAsync().GetResults()
    Dim messageDialog As New MessageDialog(link.ToString())
    messageDialog.ShowAsync()
    args.ShareOperation.ReportCompleted()
End Sub

And that’s all you need!

Testing the App

  1. Deploy your app to your phone (or the simulator)
  2. Launch Internet Explorer, and navigate to a webpage
  3. Choose the Share option from the slide-up menu at the bottom of the screen (Note: Share is greyed out until the page finishes loading)
  4. Select your app as the target.

You should see the popup message appear with the URL that was shared, then you will be returned to Internet Explorer.

Note: If your app doesn’t show up on the share target list, double-check that you’ve allowed the app to be a share target.

 

How does it work? 

Now that you have it working I will explain the code so you can understand what is happening.

OnShareActivated automatically runs when your app is launched as a share target.

Line 1: this extracts the data we want from the shared data bundle (ShareOperation.Data) sent to our app. In this example we knew we could only receive a hyperlink, so we just went and extracted a hyperlink. You can alternately use ShareOperation.Data.Contains() to determine if the data you want is present (e.g. if your app can receive different data types).

Line 2: & 3: Create and display a message dialog to the user with a string extracted from the shared data. 

Line 4: This tells the OS that you’ve handled the sharing. Your app window is closed and the user is returned to the originating app.