Opening and creating a file

In this recipe, we will learn how to open a file from local file storage and how to save the user settings to local file storage.

Getting ready

  1. Open Visual Studio for Phone 7 and create a Windows Phone Application. Name the application Ch2_Recipe2 and click on OK.
  2. After you open the project, just press F5 and run it to make sure you don't get any error.

How to do it...

Let's build a simple page with a textbox to enter text to save and a text block to display the saved text in the local file storage.

  1. Open the MainPage.xaml file and change the application title and page title to MY RECIPES and iFileStorage respectively:
    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
    <TextBlock x:Name="ApplicationTitle" Text="MY RECIPES" Style="{StaticResource PhoneTextNormalStyle}"/>
    <TextBlock x:Name="PageTitle" Text="iFileStorage" Margin="9,- 7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>
    
  2. Next, add a text block and a textbox within the ContentPanel grid as follows:
    <TextBlock x:Name ="tbName" Text ="Name:" Grid.Row="1" Grid.Column ="0"/>
    <TextBox x:Name ="tbNameContent" Grid.ColumnSpan="2" Text ="" Grid.Row="1" Grid.Column ="1" MaxHeight="100" VerticalAlignment="Top"/>
    
  3. Now let's add a TextBlock with the name tbFileStored to display what was stored in the file:
    <TextBlock x:Name ="tbStoredNames" Text ="Stored File:" Grid.Row="2" Grid.Column ="0"/>
    <TextBlock x:Name ="tbStoredNamesList" Text ="" Grid.Row="2" Grid.Column ="1"/>
    
  4. Open the MainPage.xaml.cs file and add the following two namespaces:
    using System.IO.IsolatedStorage;
    using System.IO;
    
  5. Add a string constant to store the name of the file. We will save it in the local storage. For this recipe we will use the name myfile1.txt:
    const string FILENAME = "myfile1.txt";
    
  6. Now we shall add a method to open the file from the local storage and display it in our text block:
    private void ReadFromFile()
    {
    using(var localStore = IsolatedStorageFile.GetUserStoreForApplication())
    {
    //check if the file exists
    if (localStore.FileExists(FILENAME))
    {
    //using the stream reader class open the file
    using (StreamReader sr = new StreamReader(localStore.OpenFile(FILENAME, FileMode.Open, FileAccess.Read)))
    {
    //just assign to the Text Block
    tbFileStored.Text = sr.ReadToEnd();
    }
    }
    else //if there is no file found
    tbFileStored.Text = "No Data Stored";
    }
    }
    
  7. Now that we have a method to open the file and display it, let's call this in the MainPage constructor as shown in the partial code snippet below:
    // Constructor
    public MainPage()
    {
    InitializeComponent();
    ReadFromFile();
    …
    
  8. Press F5 and run; you will see No Data Stored, as shown in the following screenshot. This is because we didn't save anything in the local storage.
    How to do it...
  9. Now add a button with the name btnSaveToFile. When you select the Click property of the button in the XAML, you will get an option to create a new event method; name it btnSaveToFile_Click:
    <Button x:Name="btnSaveToFile" Grid.Row="3" Grid.ColumnSpan="2" Content="Save Settings To A File" MaxHeight="100" Click="btnSaveToFile_Click" />
    
  10. Now go to MainPage.xaml.cs, and add the following code to save the file to btnSaveToFile_Click:
    private void btnSaveToFile_Click(object sender, RoutedEventArgs e)
    {
    using(var localStore = IsolatedStorageFile.GetUserStoreForApplication())
    {
    //using the StreamWriter class, open the file if it already exists if not create a new file
    using (StreamWriter sw = new StreamWriter(localStore.OpenFile(FILENAME, FileMode.OpenOrCreate, FileAccess.Write)))
    {
    // let's load the file read into our text block
    sw.WriteLine(tbNameContent.Text);
    }
    }
    // now call the ReadFromFile method to display the content of the file
    ReadFromFile();
    }
    
  11. Press F5 and run. Now type in some text in the Name textbox and click on the Save Settings To A File button. Now you should see the saved name in the textblock
    How to do it...

How it works...

In order to read from the file storage, we first check if the file exists in the storage. If it exists then we open it to read it, otherwise we create a file in the root folder.

Once the file is opened for reading, we use the ReadToEnd method to load the content of the text file to the text block.

In order to save the file to storage we perform similar steps to reading the file, but we use the StreamWriter class to open the file in write mode and then we use the WriteLine method to write it to the storage file.

There's more...

You can learn more about the IsolatedStorageFile classes at the following MSDN address: http://msdn.microsoft.com/en-us/library/ff626519(v=VS.92).aspx.

See also

In the recipe titled Saving a background image to local storage in this chapter, we will learn how to save an image or picture to isolated storage. Also, check Chapter 3, XML as a Data Store, to learn how to serialize and deserialize objects to local XML files.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset