File Handling in Isolated Storage in Silver Light

No.of Views1855
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  16 Feb 2010 00:02:55
Tag : Silver Light and XAML , How to
File Handling in Isolated Storage in Silver Light
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective:


This article will explain,
1. How to create a text file in IsolatedStorageFile of a SilverLight 2 application.
2. How to write into a text file in IsoltaedStorageFile.
3. How to read a text file from IsolatedStorageFile.
4. How to delete a file from IsolatedStorageFile.
Please follow, the below steps
Click here to Download Source code of this article.

Step 1:

Create a SilverLight application. By selecting File->New->Project->SilverLight-> SilverLight Application.

Step 2:
Design the XAML page. I am creating three buttons for the purpose of Read, Write and Delete File. There are two text boxes. One to get filename input and other for displaying content from the file and saving content from that text box.

Image loading....

Complete XAML code is as follows,

MainPage.Xaml

{codecitation class="brush: xml; gutter: true;" width="750px"}

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Class="FileReadingandWritingwithIsolatedStorage.MainPage"
Width="Auto" Height="Auto" mc:Ignorable="d">


<Grid x:Name="LayoutRoot" Height="400" Width="600">

<Grid.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF000000"/>
<GradientStop Color="#FFE9DDDD" Offset="1"/>
</LinearGradientBrush>
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="0.175*"/>
<RowDefinition Height="0.182*"/>
<RowDefinition Height="0.642*"/>
</Grid.RowDefinitions>
<TextBox x:Name="txtFileLabel" HorizontalAlignment="Left" Margin="17,18,0,17" Width="188" FontSize="18" FontWeight="Normal" Text="File Name" TextWrapping="Wrap" Opacity="0.3" Background="#FF808080"/>
<TextBox x:Name="txtFileName" Margin="252,18,48,17" Width="300" FontSize="18" FontWeight="Bold" Text="" TextWrapping="Wrap"/>
<Button x:Name="btnRead" HorizontalAlignment="Left" Margin="17,23,0,8" Width="180" FontSize="18" FontWeight="Bold" Grid.Row="1" Content="Read" Click="btnRead_Click"/>
<Button x:Name="btnWrite" Margin="0,23,36,8" Width="180" FontSize="18" FontWeight="Bold" Grid.Row="1" Content="Write" Click="btnWrite_Click" d:LayoutOverrides="Width" HorizontalAlignment="Right"/>
<TextBox x:Name="txtContent" Margin="30,22,45,34" Grid.Row="2" Text="" TextWrapping="Wrap" FontSize="9"/>
<Button x:Name="btnDelete" Margin="235,23,251,8" Grid.Row="1" Content="Delete File" FontWeight="Bold" FontSize="18" Click="btnDelete_Click"/>

</Grid>
</UserControl>


{/codecitation}

Image loading...

Step 2:
Now, writing the code behind to handle the Read and Write Operation. I am using IsolatedStorageFIle class to perform file handling operations.

IsolatedStorageFile
1. This class is inside the namespace System.IO.IsolatedStorage
2. We could set domain of IsolatedStorageFile either for SilverLight website or for SilverLight Application.

Both options are depicted in below images.

Image loading....

Image Loading...

3.There are many methods exist inside this to work with File operations. For example, create directory, create file, delete directory, delete file etc.

Below image is depicting all the available methods of IsolatedStorageFile class. Store is instance of this class in below image.

Image Loading...

How to write into the file?

{codecitation class="brush: csharp; gutter: true;" width="650px"}private void btnWrite_Click(object sender, System.Windows.RoutedEventArgs e)
{

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist , we are creating one for you ");
IsolatedStorageFileStream file = store.CreateFile(txtFileName.Text);
file.Close();
}
using (StreamWriter sw = new StreamWriter(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = "";
txtFileName.Text = "";
MessageBox.Show("File Writen");
}
}


{/codecitation}

Explanation
1.StreamWriter is being used to write into the file.
2.StreamWriter is inside the namespace System.IO.
3. We are opening the ISolatedStorageFile for the SilverLight Application.
4. We are checking, that if file name provided by user does not exist then create a new one with the provided name.
5. We are opening the file in Write Mode and writing the stream into that.

How to Read from the file?

{codecitation class="brush: csharp; gutter: true;" width="650px"}

private void btnRead_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist ");
txtFileName.Text = "";
}

else
{
using (StreamReader sr = new StreamReader(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.ReadWrite)))
{
txtContent.Text = sr.ReadToEnd();
}

}
}
}


{/codecitation}

Explanation
1.StreamReader is being used to read from the file.
2.StreamReader is inside the namespace System.IO.
3. We are opening the ISolatedStorageFile for the SilverLight Application.
4. We are checking, that if file name provided by user does not exist then displaying the message that file name does not exist.
5. We are opening the file in Read Mode and reading the stream into a string.

How to delete file?

{codecitation class="brush: csharp; gutter: true;" width="650px"}

private void btnDelete_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist ");

}
else
{
store.DeleteFile(txtFileName.Text);
MessageBox.Show("Deleted");
}

txtFileName.Text = "";
}
}

{/codecitation}

Explanation
1. We are calling the DeleteFile method on instance of ISolatedStorageFile.

Complete code is as below

MainPage.xaml.cs

{codecitation class="brush: csharp; gutter: true;" width="700px"}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.IO.IsolatedStorage;

namespace FileReadingandWritingwithIsolatedStorage
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

private void btnRead_Click(object sender, System.Windows.RoutedEventArgs e)
{

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{

if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist ");
txtFileName.Text = "";

}

else
{
using (StreamReader sr = new StreamReader(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.ReadWrite)))
{
txtContent.Text = sr.ReadToEnd();
}

}
}
}

private void btnWrite_Click(object sender, System.Windows.RoutedEventArgs e)
{

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist , we are creating one for you ");
IsolatedStorageFileStream file = store.CreateFile(txtFileName.Text);
file.Close();
}
using (StreamWriter sw = new StreamWriter(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = "";
txtFileName.Text = "";
MessageBox.Show("File Writen");
}
}



private void btnDelete_Click(object sender, System.Windows.RoutedEventArgs e)
{

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist ");

}
else
{
store.DeleteFile(txtFileName.Text);
MessageBox.Show("Deleted");
}

txtFileName.Text = "";
}
}
}
}

{/codecitation}

Step 3:
Press F5 to run with debug.

Image Loading....

Conclusion:
I have explained in this article, about various file options in isolated storage. Please download ZIP file for better understanding and reference.


Thanks for Reading. Happy Coding


About the Author


Dhananjay Kumar
Description :I done my engineering from Anand Engineering college Agra in 2007. I am MCTS WCF, MCTS MOSS Development, I am MCTS Web Development . I am native of Jamshedpur. Currently Please feel free to contact me regarding any clarification of my article at Dhananjay.25july@gmail.com

Occupation : Software Engineer
Company : UST Global.
Location : India
Follow me at twitter : http://twitter.com/dhananjay25


 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top