Save User Data to Local Application Storage in Windows Store App Using C#

Today we will learn how to store and retreive user details from local application data storage.

Sometimes we want to save user-related data in some 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 taks. Normally we want to store user login information for his/her session, so that we can check whether he/she is authorized or not.

In Windows 8 Store apps, the developer has the ability to save user data so it can be retrieved any time during running the application or even again in running mode after being closed by the user. The data stored in Application local 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 local storage is never lost untill the application is removed or uninstalled from the computer system.

In this article we are trying to save user data to Local 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 Local Application data storage.

First create a Blank Application using C# and XAML.

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>

Now, I need an entity for the values of these controls and then save the entire bucket to Local Application Storage. So, I'm going to create a UserDetails class.

public class UserDetail

{

    public int Id { get; set; }

    public string Name { get; set; }   

}

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.

UserDetail Stats = new  UserDetail();

private async void login_Click_1(object sender, RoutedEventArgs e)

{ 

     Stats.Name = NameTextBox.Text;

     Stats.Id = int.Parse(IdTextBox.Text);

     await SaveAsync();

     this.Frame.Navigate(typeof(next));                
}

You all know that everything in Windows 8 Store apps is asynchronous, so we'll see the async and await keywords in these apps.

In the SaveAsync method we will serialize the data to be saved into Local Application Storage.
 

StorageFile userdetailsfile = await ApplicationData.Current.LocalFolder.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(UserDetail));

    serializer.WriteObject(outStream.AsStreamForWrite(), Stats);

    await outStream.FlushAsync();

}


In the preceding code first we get the local folder of local 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.

In the Next Page where we naviagte 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)

{

await RestoreAsync();
}

Here is the code of the ReterieveAsync() method where I read the file from the Local Folder, deserialize it's contents and then set the instance of UserDetails with the values that were saved earlier.

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("UserDetails");    

if (file == null) return;

IRandomAccessStream inStream = await file.OpenReadAsync();                      

    // Deserialize the Session State.

DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetail));

var StatsDetails = (UserDetail)serializer.ReadObject(inStream.AsStreamForRead());

inStream.Dispose();          

UserName.Text ="Welcome "+ StatsDetails  .Name;

UserProfileId =  StatsDetails.Id;
 

This is what my app looks like before I close  or navigate it myself.

Local-Storage-Location-In-Windows8-Apps (1).jpg

Up Next
    Ebook Download
    View all
    Learn
    View all