Tips, tricks, and guides for developing on modern Windows platforms
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).
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.
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);
}
}
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;
}
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.
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.
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?
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.
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
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
Hello Damien
I like your Visual studio Code Color Schemes, Please give me the Color Schemes. thank you.
Here’s a link to my font and colour settings. You should be able to import this into Visual Studio 2015:
https://onedrive.live.com/redir?resid=5AF059DA63BE71BC!983662&authkey=!AM0SceChXjYfRgg&ithint=file%2cvssettings
Thank you.
but when I will import the (fonts and colours.vssettings) file to Visual Studio 2015,the system reminder : not found the Color Schemes in the import file.
I find the problem, when I open the (fonts and colours.vssettings)file, I delete the line code[] , the file is import the VS 2015,but the color is not your article code color
My apologies, I forgot that the code on the blog uses a WordPress plugin to show the font colours, so it’s different to what I use in Visual Studio. There is no way to copy the colours from the blog plugin. However, you might find a similar theme at http://studiostyl.es/. I got a theme from there and customised it to use as my own Visual Studio theme, and I’m very happy with the results.
Hi Damien
it doesn’t matter, I create new code color schemes in my Visual Studio 2015 already. Thank you.
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,
Typecast correction in below statement.
stream.Write(fileBytes, (int)fileSize, fileBytes.Length);
Thanks,