All about WP7 Isolated Storage - File manipulations
published on: 5/11/2011 | Views: N/A | Tags: IsoStore
by WindowsPhoneGeek
This is the 10th article from the "All about WP7 Isolated Storage " series of short articles focused on real practical examples with source code rather than a plain theory. I am going to talk about how to perform the different file manipulations in Isolated Storage like: add, remove, delete files, etc.
- All about WP7 Isolated Storage - intro to Isolated Storage
- All about WP7 Isolated Storage - Creating Folders and files
- All about WP7 Isolated Storage - Store data in IsolatedStorageSettings
- All about WP7 Isolated Storage - Read and Save Text files
- All about WP7 Isolated Storage - Read and Save XML files using XmlSerializer
- All about WP7 Isolated Storage - Read and Save XML files using XmlWriter
- All about WP7 Isolated Storage - Read and Save Images
- All about WP7 Isolated Storage - Read and Save Captured Image
- All about WP7 Isolated Storage - Read and Save Binary files
- All about WP7 Isolated Storage - File manipulations
- All about WP7 Isolated Storage - Recommendations and Best Practices
- All about WP7 Isolated Storage - open source Databases and Helper libraries
T.o begin with lets first create a Windows Phone 7 application project. Next include the following namespaces in MainPage.xaml.cs (alternatively you can use the code in another page):
using System.IO.IsolatedStorage; using System.IO; using System.Windows.Resources;
We will also use the following constants:
private const string FileName = "SomeFile.txt"; private const string FolderName = "SomeDir"; private string FilePath = System.IO.Path.Combine(FolderName, FileName);
Write/Create File in IsolatedStorage
In this example I will demonstrate how to create a new text file in IsolatedStorage and how to add some data into it. At first we will create a method called CreateNewFile which will accept as parameter the desired filePath. The most important thing here is not to forget to check if the target directory exists in IsolatedStorage (this is the case when using composite paths including directories, like for example: SampleDir1/File1.txt ). The method can be used with simple file paths (ex. File1.txt) and composite one(ex. SampleDir1/File1.txt) as well.
private void CreateNewFile(string filePath)
{
StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
string directoryName = System.IO.Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(directoryName) && !myIsolatedStorage.DirectoryExists(directoryName))
{
myIsolatedStorage.CreateDirectory(directoryName);
}
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(filePath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
string someTextData = "This is some text data to be saved in a new text file in the IsolatedStorage!";
writer.WriteLine(someTextData);
}
}
}
}
Sample usage:
private void btnWrite_Click(object sender, RoutedEventArgs e)
{
this.CreateNewFile(FilePath);
}
Check if a file/directory exists
You can check is a particular file exists in this way:
myIsolatedStorage.FileExists(filePath)
You can check is a particular directory exists in this way:
myIsolatedStorage.DirectoryExists(directoryName)
Read File from IsolatedStorage
In this example I will demonstrate how to read data from an existing text file in IsolatedStorage. At first we will create a method called ReadFile which will accept as parameter the desired filePath. The method can be used with simple file paths (ex. File1.txt) and composite one(ex. SampleDir1/File1.txt) as well.
private void ReadFile(string filePath)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(filePath))
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fileStream))
{
this.text.Text = reader.ReadLine();
}
}
}
else
{
MessageBox.Show("File not found!");
}
}
}
Sample usage:
private void btnRead_Click(object sender, RoutedEventArgs e)
{
this.ReadFile(FilePath);
}
Edit File in IsolatedStorage
In this example I will demonstrate how to edit an existing text file in IsolatedStorage. At first we will create a method called EditExistingFile which will accept as parameter the desired filePath and insetedText. The method can be used with simple file paths (ex. File1.txt) and composite one(ex. SampleDir1/File1.txt) as well.
private void EditExistingFile(string filePath, string insetedText)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//Open existing file
if (myIsolatedStorage.FileExists(filePath))
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(filePath, FileMode.Open, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
string someTextData = insettedText;
writer.Write(someTextData);
writer.Close();
}
}
}
}
}
Sample usage(In this example "Some new Text!" will be added to the text file data):
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
this.EditExistingFile(FilePath, "Some new Text!");
}
Delete File in IsolatedStorage
In this example I will demonstrate how to delete a file in IsolatedStorage. Just check if the file exists and after that use myIsolatedStorage.DeleteFile(FilePath). The method can be used with simple file paths (ex. File1.txt) and composite one(ex. SampleDir1/File1.txt) as well.
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(FilePath))
{
myIsolatedStorage.DeleteFile(FilePath);
}
}
}
Clear IsolatedStorage
NOTE: You'll lose all isolated storage for all apps by restarting the emulator.
However if you still want to clear the isolatedStorage programatically here is the code:
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
store.Remove();
}
In this article I talked about how to perform the different file manipulations in Isolated Storage.This post is some kind of summary of the techniques used so far in this series. Here is the full source code:
Stay tuned with the rest of the posts.I hope that the article was helpful.
You can also follow us on Twitter @winphonegeek
Comments
IsolatedStorage explorer
posted by: Samuel Blanchard on 11/21/2011 8:09:14 AM
Nice article !
If you want to see the content of your isolatedstorage, the easy and fastest way is to use IsoStoreSpy. With this application you could explore the isolated storage of yours MANGO and NODO applications without install anything on the phone. You can also explore the database SqlCE embedded in your apps, modifiy Text file and see image. it's opensource and free :)
IsolatedStorage explorer
posted by: Samuel Blanchard on 11/21/2011 8:10:42 AM
best with the url :) http://isostorespy.codeplex.com
Exception when trying to delete a file
posted by: Andrei on 3/13/2012 11:15:18 PM
Hi!
I'm using very similar code to what you show here for deleting a file from IsolatedStorage, but I always get an "An error occurred while accessing IsolatedStorage" exception using the emulator. Do you have any idea what could be wrong?
Thank you!
MR
posted by: Charles Khoury on 3/24/2012 1:47:46 PM
i want to know how to list all folders and files in the isolated storage
thank you,
Our Top Articles & Free books
- Our FREE e-book: "Windows Phone Toolkit In Depth" 2nd edition
- 400+ Windows Phone Development articles in our Article Index
- 21 WP7 Toolkit in Depth articles covering all controls
- 12 WP7 Coding4Fun Toolkit in Depth articles covering all controls
- Performance Tips when creating WP7 apps
- Creating a WP7 Custom Control in 7 Steps
- WP7 working with VisualStates: How to make a ToggleSwitch from CheckBox
- What makes a WP7 App successful
- Creating theme friendly UI in WP7 using OpacityMask
- Implementing Windows Phone 7 DataTemplateSelector and CustomDataTemplateSelector
- All about Splash Screens in WP7 – Creating animated Splash Screen
- Getting Started with Unit Testing in Silverlight for WP7
- WP7 WatermarkedTextBox custom control
Our Top Tips & Samples
- All about WP7 Isolated Storage series
- WP7 Dynamically Generating DataTemplate in code
- 5 tips for a successful WP7 Marketplace submission
- WP7: Navigating to a page in different assembly
- WP7 ContextMenu: answers to popular questions
- WP7 ListBox: answers to popular questions
- WP7 working with Images: Content vs Resource build action
- WP7 Element Binding samples
- WP7 working with XML: reading, filtering and databinding
- Drawing in WP7: #2 Drawing shapes with finger
- WP7 TextBox Light theme problems - the solution
- Changing the WP7 Panorama Background Image dynamically with Animation
