In almost all the apps that are developed, some sort of data needs to be stored on the device either temporarily or permanently. There are lots of options of storing data when working on Windows Phone platform. In my earlier tutorials, we looked at how to create a simple Windows Phone app and performing page navigation. In this post, lets take a look at how to Read and Write files to the Local Folder in Windows Phone.
Open Visual Studio 2013/2012 and Create a New Windows Phone App project and name it “LocalStorageWpApp”. We will be creating a small application where we will read and write contents in a local file on Windows Phone.
Once the default solution is create, open MainPage.xaml and rename the page title to say “Local Storage”. Add the below XAML code to the ContentPanel Grid.
<StackPanel > <TextBlock Text="FileName" /> <TextBox Name="txtFileName" /> <TextBlock Text="Content" /> <TextBox Name="txtFileContent" Height="200" TextWrapping="Wrap" /> <Button Content="Create File" Name="btnCreate" Tap="btnCreate_Tap" /> <Button Content="View Files" Name="btnView" Tap="btnView_Tap" /> </StackPanel>
We have added the Textboxes where the user can enter the filename as well as the file content which is to be stored in the file. Once the user hits the “Create File” button, a new file will be created in the local folder with the filename specified. We call the “SaveFile” function which is implemented as shown below
private async void SaveFile() { try { StorageFolder folder = ApplicationData.Current.LocalFolder; if(folder != null) { StorageFile file = await folder.CreateFileAsync(txtFileName.Text, CreationCollisionOption.ReplaceExisting); byte[] fileContent = Encoding.UTF8.GetBytes(txtFileContent.Text.ToCharArray()); Stream fileStream = await file.OpenStreamForWriteAsync(); fileStream.Write(fileContent, 0, fileContent.Length); fileStream.Flush(); fileStream.Close(); MessageBox.Show("File Has Been Created"); txtFileContent.Text = ""; txtFileName.Text = ""; } } catch (Exception ex) { // Some Exception handling code } }
The “Windows.Phone.Storage” namespace contains the “StorageFolder” and “StorgaeFile” classes which provides method for working with Files and Folders in Windows Phone Application. In the code above, we are storing some string content in a file in local application data folder. The StorageFolder class gives access to the root container and allows operations like creating and reading files. It also contains different functions for creating as well as deleting files/folders.
Once we get a handle to the Local Folder using the ApplicationData instance, we call the “CreateFileAsync” function and pass the name of the file. We also specify an additional Collision Option through the CreateCollisionOption enumeration. In this case, we are specifying the file should be replaced if a file with the same name already exists. Since the “CreateFileAsync” function is asynchronous it is necessary to execute these using the “await” and “async” keywords.
Once the file is created, we use the “OpenStreamForWriteAsync” function to get a stream which can then be used to write content to the file. This is similar to what we normally used while working with files in C#. If the file is successfully created, we display a message.
As the files are now getting created, lets display the list of files to the user which are present in the Local Folder. Right Click on Project –> Add –>New Item –> Windows Phone Portrait Page and name it ViewFiles.xaml. In this page, we will display the List of files which we are creating in the Local Folder. In the “View Files” button tap event add the below code which navigates the user to our newly added page.
private void btnView_Tap(object sender, System.Windows.Input.GestureEventArgs e) { NavigationService.Navigate(new Uri("/ViewFiles.xaml", UriKind.Relative)); }
Open ViewFiles.xaml and add the following XAML to the ContentPanel grid.
<phone:LongListSelector Margin="0,-10,-22,2" SelectionChanged="LongListSelectorFiles_SelectionChanged" Name="llsFiles" > <phone:LongListSelector.ItemTemplate> <DataTemplate> <StackPanel > <TextBlock Text="{Binding Name}" TextWrapping="Wrap" Margin="10,35" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="{StaticResource PhoneFontSizeLarge}" /> </StackPanel> </DataTemplate> </phone:LongListSelector.ItemTemplate> </phone:LongListSelector>
We are going to display the List of File Names using the LongListSelector control. In the code behind file, we handle the “OnNavigatedTo” event and call the “GetFilesList” function which has below code
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); GetFilesList(); } public async void GetFilesList() { StorageFolder folder = ApplicationData.Current.LocalFolder; IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(); FilesList = new List<StorageFile>(files); llsFiles.ItemsSource = FilesList; }
In the “GetFilesList” function, we again obtain a handle to the local folder and get a list of files in the current folder using the “GetFilesAsync” method. It returns an IReadOnly List of ‘StorageFile’ types which we then save to the FilesList variable. We then set the ItemSource property of our LongListSelector to “FilesList”. This displays the list of file names.
Lets run the app in our emulator. Once the application starts, enter the file name and some text in the Content Text box and click on “Create File”. The File will be created. Clicking the “View Files” button takes us to separate page which list down the name of the files which we have created.
Lets add the functionality display the contents of the file which the user selects from the list. Add a new ‘Windows Phone Portrait Page’ to the project and name it “SinglePage.xaml”. We will handle the “SelectionChanged” event of the LongListSelector.
private void LongListSelectorFiles_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (llsFiles.SelectedItem != null) { var file = llsFiles.SelectedItem as StorageFile; NavigationService.Navigate(new Uri("/SingleFile.xaml?filename=" + file.Name, UriKind.Relative)); llsFiles.SelectedItem = null; } }
In the above code, we use the ‘SelectedItem’ property which contains the object which the user selected and typecast it to ‘StorageFile’ type as our LongListSelector is bound to List<StorageFile”> object. Once we get the selected object, we use the ‘Name’ property to get the file name and we pass it as a query string to the “SinglePage.xaml”.
Open “SinglePage.xaml” and add the below XAML to the ContentPanel Grid.
<StackPanel> <TextBlock Text="File Name" /> <TextBox Name="txtFileName" IsReadOnly="True" /> <TextBlock Text="Content" /> <TextBox Height="200" Name="txtFileContent" /> <Button Content="Update" Name="btnUpdate" Tap="btnUpdate_Tap" /> <Button Content="Cancel" Name="btnCancel" Tap="btnCancel_Tap" /> </StackPanel>
This is similar to our main page. We are displaying the name of the file as well as its content to the user. The user can change the content and update the same and the file will be updated. Add the below code to the “SinglePage.xaml.cs” files to read the content of the file which the user has selected.
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string filename; if(NavigationContext.QueryString.TryGetValue("filename",out filename)) { DisplayFile(filename); } } private async void DisplayFile(string filename) { StorageFolder local = ApplicationData.Current.LocalFolder; if(local != null) { try { Stream file = await local.OpenStreamForReadAsync(filename); StreamReader sr = new StreamReader(file); string content = sr.ReadToEnd(); txtFileContent.Text = content; txtFileName.Text = filename; sr.Close(); file.Close(); } catch(Exception ex) { // SOme Exception Handling } } }
In the ‘OnNavigatedTo’ event, we read the file name from the query string and pass it to the function. In the “DisplayFile” function, we use the “OpenStreamForReadAsync” function to get a reference to the stream. We then create an instance of the StreamReader class to read the content of the file and we are displaying the same in the Textbox.
To Update the file, we can use the similar function which we will be almost same as the “SaveFile” function we saw earlier. You can run the app in the emulator. On clicking on a file name, you will be redirected to different page which will list the content of the file.
In the next post, we will take a look at storing data in Memory card and local databases.
Pingback: Using Isolated Storage in Windows Phone App | Coding Paradox
Pingback: Using Local Database in Windows Phone Apps | Coding Paradox