Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

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.

Tags: , , , ,

13 Responses to “Read and Write Text Files (Windows 8.1 / Phone 8.1 Universal Apps)”

  1. Himanshu says:

    Apologies for silly question but even after I create a new page & put your code in it,it’s not working & wants me to put ” ;” after “tasks” in the “writing” function.

    • Damien says:

      What exactly is the error message? Make sure you have all the code on your page within the correct curly braces. Have you added the namespaces? Is your project targeting WinRT for Universal Apps?

  2. Mike says:

    I would like to thank you for this. This helped with a Windows IoT core app I am writing for the Raspberry PI 2 B board. Using the standard file i/o stream classes I was getting access denied. Using this and (treating these apps as 100% UWP) I’m able to read/write to the apps storage folder.

  3. Alex says:

    Hello,
    The code is not working for me..
    I’m developping a Windows Phone 8.1 project.
    Where is the place to put the .txt file on my project? I have the file in my project root and I’m getting an error when I call readStringFromLocalFile(“filename.txt”)

    the error happens inside of readStringFromLocalFile method.

    Can you help me?
    Thanks

    • Damien says:

      This technique is for reading files you create from your app and save to the app’s local folder. Reading a file from the solution/project is a bit different. I think it will work if you just use the correct path for the filename: “ms-appx:///foldername/filename.txt” (e.g. if your file is in the project root folder it would be “ms-appx:///filename.txt”. I think you will also need to set the file’s build action property to “Content” (right-click the file inside Visual Studio’s Solution Explorer, and choose Properties).

      There’s more detail at the following site: http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html

  4. Sniper says:

    Hello Damien
    I like your Visual studio Code Color Schemes, Please give me the Color Schemes. thank you.

  5. Dipen says:

    Thanks Damien for sharing this useful code. Using stream.Write(), I’m able to write my data into the file. However, the code seems to always begin from the starting of the file and hence, my data gets over written. Need some assistance on appending the data in to the file.

    I tried the below code but it generates an exception.

    var basicFileProperty = await file.GetBasicPropertiesAsync();
    var fileSize = basicFileProperty.Size;

    stream.Write(fileBytes, fileSize, fileBytes.Length);

    Thanks,

Leave a Reply

Your email address will not be published.