Today we will learn how to store and retrieve files to/from temporary application data storage in Windows 8 Apps. In my previous article we learned about Local Application Storage Location in Windows 8 Apps.
Sometimes we want to save user-related data for a short period in some kind of application storage during his/her session. It is necessary to save user session data during navigation though various pages in an application. Anytime and for any page we need this user session data to do some processing. Normally we want to store user login information for his/her session, so that we can check whether he/she is authorized or not. The data in Application Temporary storage is lost anytime the application is removed or uninstalled from the computer system.
I suggest you to not save important information in this storage since it is often lost for various reasons such as low memory.
In Windows 8 Store apps, the developer has the ability to save user data so it can be retrieved anytime when running the application or even again in running mode after being closed by the user. The data stored in Application Temporary storage is saved even when an application is not in running mode and you can also fetch data from it when running the app again. The data in Application Temporary storage is lost anytime the application is removed or uninstalled from the computer system.
In this article we are trying to save user data to Temporary Application data storage and also retrieve from it. So, now we proceed to create a Windows 8 Store blank application and save user details to Temporary Application data storage.
Step 1
First create a Blank Application using C# and XAML.
Step 2
I've created a simple blank XAML page:
<Page
x:Class="savinguserdataonsuspended.MainPage"
IsTabStop="false"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:savinguserdataonsuspended"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Canvas>
<TextBox Canvas.Left="249.977" TextWrapping="Wrap" Canvas.Top="67.89" x:Name="IdTextBox"
RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" Width="259.477"
d:LayoutRounding="Auto"/>
<TextBlock Canvas.Left="90" FontSize="30" TextWrapping="Wrap" Text="Email ID"
Canvas.Top="75"/>
<TextBox Canvas.Left="250" TextWrapping="Wrap" Canvas.Top="130" x:Name="NameTextBox"
Width="261"/>
<TextBlock Canvas.Left="85" TextWrapping="Wrap" Text="Name" FontSize="30" Canvas.Top="129"/>
<Button x:Name="save" Content="Login" Click="save_Click_1" FontSize="25" Canvas.Top="210"
Canvas.Left="187" Height="62" Width="154"></Button>
</Canvas>
</Grid>
</Page>
Step 3
Now, I need an entity for the values of these controls and then save the entire bucket to Temporary Application Storage. So, I'm going to create a UserDetails class.
public class UserDetail
{
public int Id { get; set; }
public string Name { get; set; }
public bool HasValue { get; set; }
}
Step 4
I use the Button's click events to keep the instance of UserDetails updated and call a SaveAsync() method and then, navigate to another page.
private async void login_Click_1(object sender, RoutedEventArgs e)
{
Stats.Name = NameTextBox.Text;
Stats.Id = int.Parse(IdTextBox.Text);
SaaveAsync();
this.Frame.Navigate(typeof(LandingPage));
}
You all know that everything in Windows 8 Store apps is asynchronous, so we'll see the async and await keywords in these apps.
Step 5
You have to include the Namespace to access the Storage location of Application data.
Using Window.Storage;
Using Window.Storage.Streams;
Step 6
In the SaveAsync method we will serialize the data to be saved into Temporary Application Storage.
StorageFile userdetailsfile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("UserDetails",
CreationCollisionOption.ReplaceExisting);
IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);
using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
{
// Serialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetails));
serializer.WriteObject(outStream.AsStreamForWrite(), Stats);
await outStream.FlushAsync();
}
In the preceding code first we get the Temporary folder of Temporary storage and then create a file using the CreateFileAsync() method also user the parameter ReplaceExisting if the file already exists. Then we open it using OpenAsync in the read/write mode. Then I serialize the object using the DataContractSerializer class and write this serializer obect to a file using the WriteObject method.
Step 7
In the next page where we naviagte to after login we call the ReterieveAsync() method to restore the value back to a bucket at the OnNavigatedTo event of the page.
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
RestoreAsync();
}
Step 8
Here is the code of the ReterieveAsync() method where I read the file from the Temporary Folder, deserialize it's contents and then set the instance of UserDetails with the values that were saved earlier.
StorageFile file = await ApplicationData.Current.TemporaryFolder .GetFileAsync("UserDetails");
if (file == null) return;
IRandomAccessStream inStream = await file.OpenReadAsync();
// Deserialize the Session State.
DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetails));
var name = (UserDetails)serializer.ReadObject(inStream.AsStreamForRead());
inStream.Dispose();
UserName.Text ="Welcome "+Stats.Name;
UserProfileId = Stats.Id;
This is what my app looks like before I close or navigate it myself.