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.
