In any application, one of the most important thing is the data. If you are .net developer, you might know about the isolated storage and the same concept follows through the Universal Windows Platform (UWP) applications.
These are the areas where your application can access the data. The application contains some area, which is private to that particular application and is inaccessible to the others, but there are many other areas, where you can store and save your data inside a file.
Given below are the brief descriptions of each folder.
S.No. | Folder & Description |
---|---|
1 | App package folder Package manager installs all the app’s related files into the App package folder, and app can only read data from this folder. |
2 | Local folder Applications store local data into a local folder. It can store data up to the limit on the storage device. |
3 | Roaming folder Setting and properties related to application is stored in roaming folder. Other devices can also access data from this folder. It has limited size up to 100KB per application. |
4 | Temp Folder Use of temporary storage and there is no guarantee that it will still be available when your application runs again. |
5 | Publisher Share Shared storage for all the apps from the same publisher. It is declared in app manifest. |
6 | Credential Locker Used for secure storage of password credential objects. |
7 | OneDrive OneDrive is free online storage that comes with your Microsoft account. |
8 | Cloud Store data on the cloud. |
9 | Known folders These folders already known folders such as My Pictures, Videos, and Music. |
10 | Removable storage USB storage device or external hard drive etc. |
In Windows 8, new APIs were introduced for file handling. These APIs are located in the Windows.Storage and Windows.Storage.Streams namespaces. You can use these APIs instead of the System.IO.IsolatedStorage namespace. By using these APIs, it will be easier to port your Windows Phone app to the Windows Store, and you can easily upgrade your applications to future versions of the Windows.
To access local, roaming or temp folders, you need to call these APIs −
StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder; StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
To create a new file in a local folder use the following code −
StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile textFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
Here is the code to open the newly created file and write some content in that file.
using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite)) { using (DataWriter textWriter = new DataWriter(textStream)){ textWriter.WriteString(contents); await textWriter.StoreAsync(); } }
You can open the same file again, from the local folder as shown in the code given below.
using (IRandomAccessStream textStream = await textFile.OpenReadAsync()) { using (DataReader textReader = new DataReader(textStream)){ uint textLength = (uint)textStream.Size; await textReader.LoadAsync(textLength); contents = textReader.ReadString(textLength); } }
To understand how the reading and writing of the data works, let us have a look at a simple example. Given below is the XAML code in which different controls are added.
<Page x:Class = "UWPFileHandling.MainPage" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local = "using:UWPFileHandling" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable = "d"> <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Button x:Name = "readFile" Content = "Read Data From File" HorizontalAlignment = "Left" Margin = "62,518,0,0" VerticalAlignment = "Top" Height = "37" Width = "174" Click = "readFile_Click"/> <TextBox x:FieldModifier = "public" x:Name = "textBox" HorizontalAlignment = "Left" Margin = "58,145,0,0" TextWrapping = "Wrap" VerticalAlignment = "Top" Height = "276" Width = "245"/>. <Button x:Name = "writeFile" Content = "Write Data to File" HorizontalAlignment = "Left" Margin = "64,459,0,0" VerticalAlignment = "Top" Click = "writeFile_Click"/> <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left" Margin = "386,149,0,0" TextWrapping = "Wrap" VerticalAlignment = "Top" Height = "266" Width = "250" Foreground = "#FF6231CD"/> </Grid> </Page>
Given below is the C# implementation for different events and also the implementation of the FileHelper class for reading and writing data to the text file.
using System; using System.IO; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace UWPFileHandling { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public partial class MainPage : Page { const string TEXT_FILE_NAME = "SampleTextFile.txt"; public MainPage(){ this.InitializeComponent(); } private async void readFile_Click(object sender, RoutedEventArgs e) { string str = await FileHelper.ReadTextFile(TEXT_FILE_NAME); textBlock.Text = str; } private async void writeFile_Click(object sender, RoutedEventArgs e) { string textFilePath = await FileHelper.WriteTextFile(TEXT_FILE_NAME, textBox.Text); } } public static class FileHelper { // Write a text file to the app's local folder. public static async Task<string> WriteTextFile(string filename, string contents) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile textFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite)){ using (DataWriter textWriter = new DataWriter(textStream)){ textWriter.WriteString(contents); await textWriter.StoreAsync(); } } return textFile.Path; } // Read the contents of a text file from the app's local folder. public static async Task<string> ReadTextFile(string filename) { string contents; StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile textFile = await localFolder.GetFileAsync(filename); using (IRandomAccessStream textStream = await textFile.OpenReadAsync()){ using (DataReader textReader = new DataReader(textStream)){ uint textLength = (uint)textStream.Size; await textReader.LoadAsync(textLength); contents = textReader.ReadString(textLength); } } return contents; } } }
When the above code is compiled and executed, you will see the following window.
Now, you write something in the textbox and click “Write Data to File” button. The program will write the data into the text file in a local folder. If you click on “Read Data from File” button, the program will read the data from the same text file, which is located in the local folder and will display it on the text block.