All about WP7 Isolated Storage - Files and Folders
published on: 3/14/2011 | Views: N/A | Tags: IsoStore
by WindowsPhoneGeek
This is the second 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 creating folders and files in the Windows Phone 7 Isolated Storage.
- All about WP7 Isolated Storage - intro to Isolated Storage
- All about WP7 Isolated Storage - 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
To begin with lets first create a sample 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; using System.IO.IsolatedStorage;
Folders in the WP7 Isolated Storage
- Create Folder
In order t create a folder called "New Folder", we can just invoke the method CreateDirectory of the instance of the class IsolatedStorageFile:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
myIsolatedStorage.CreateDirectory("NewFolder");
NOTE: Instead of "NewFolder" you can specify another more composite path like for example"Folder1/Folder2/Folder3/NewFolder".
myIsolatedStorage.CreateDirectory("Folder1/Folder2/Folder3/NewFolder");
- Delete Folder
To delete a folder just invoke the DeleteDirectory of the instance of the class IsolatedStorageFile:
myIsolatedStorage.DeleteDirectory("NewFolder");
- Best Practices
- Always check if the Directory exists
myIsolatedStorage.DirectoryExists(directoryName)
- Always use try{}catch{} when working with the Isolated Storage to prevent any unexpected exception to be seen by the user. Here is an example of a method that create Directory with a given name:
public void CreateDirectory(string directoryName)
{
try
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if(!string.IsNullOrEmpty(directoryName) && !myIsolatedStorage.DirectoryExists(directoryName))
{
myIsolatedStorage.CreateDirectory(directoryName);
}
}
catch (Exception ex)
{
// handle the exception
}
}
To create a directory just call the method and add as a parameter the desired name:
this.CreateDirectory("NewFolder");
-Alternatively use the same checks when deleting folders:
NOTE: A directory must be empty before it is deleted. The deleted directory cannot be recovered once deleted.
public void DeleteDirectory(string directoryName)
{
try
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!string.IsNullOrEmpty(directoryName) && myIsolatedStorage.DirectoryExists(directoryName))
{
myIsolatedStorage.DeleteDirectory(directoryName);
}
}
catch (Exception ex)
{
// handle the exception
}
}
To delete a folder just call the method:
this.DeleteDirectory("NewFolder");
NOTE: Currently it is not possible to Rename a Directory in the Isolated Storage.
Files in the WP7 Isolated Storage
- Create File
To create a new file named "SomeFile.txt" just use the StreamWriter :
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("NewFolder\\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage));
NOTE: If you do not specify any folder then the file will be created in the root folder. You can also create files using IsolatedStorageFileStream:
IsolatedStorageFileStream stream1 = new IsolatedStorageFileStream("SomeTextFile.txt", FileMode.Create, myIsolatedStorage);

- Delete File
To delete a file from Isolated Storage just invoke the DeleteFile of the instance of the class IsolatedStorageFile:
myIsolatedStorage.DeleteFile("NewFolder/SomeFile.txt");
- Best Practices
- Always check if the Directory in which you want to create/delete a File exists
myIsolatedStorage.DirectoryExists(directoryName)
- Always check if the file already exists myIsolatedStorage.FileExists(filePath). If so you will have to delete the old file before creating a new one.
- Always use try{}catch{} when working with the Isolated Storage to prevent any unexpected exception to be seen by the user. Here is an example of a method that create Directory with a given name:
try
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile;
if (!myIsolatedStorage.DirectoryExists("NewFolder"))
{
myIsolatedStorage.CreateDirectory("NewFolder");
writeFile = new StreamWriter(new IsolatedStorageFileStream("NewFolder\\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage));
}
else
{
writeFile = new StreamWriter(new IsolatedStorageFileStream("NewFolder\\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage));
}
}
catch (Exception ex)
{
// do something with exception
}
NOTE: To completely remove all stores in the IsolatedStorage just call for store.Remove() where "store" is an instance of the IsolatedStorageFile.
In this article I talked about creating Folders and Files in the WP7 Isolated Storage. Stay tuned with the rest of the posts.
You can also follow us on Twitter @winphonegeek
Comments
Deleting folders in isolated storage
posted by: Todd on 3/23/2011 4:57:39 PM
I'm loving this series! Getting some good help, thanks. One question on deleting folders. I notice the note above that says the folder must be empty before deleting. Does this mean that you can not delete a folder that isn't empty or does it mean you will lose all info in that folder if you delete it?
I ask because I'm trying to delete a folder and it doesn't matter if I lose info or not because it is user info and code will just wait for new info or exit. I have written the code to display info saved (if any) once the page loads, if I hit delete, clear the fields and delete folder and navigate back to main page. If user navigates back to page and it is set to load info (but after deleting folder there should not be) but it is still there! my code I'm using is below, any help is greatly appreciated!
//upon page loading code
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
try
{
IsolatedStorageFile myisodir = IsolatedStorageFile.GetUserStoreForApplication();
if (myisodir.DirectoryExists("userData"))
{
LoadInfo();
}
}
catch
{
this.CreateDirectory("userData");
infoStatus.Visibility = System.Windows.Visibility.Collapsed;
}
}
//delete coding: private void AppButtonDelete_click(object sender, EventArgs e) { //Clear all Textblocks userName.Text = ""; userAge.Text = "";
//Delete User Directory
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
myStore.DeleteDirectory("userData");
//Navigate back to HomePage
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
RE:Deleting folders in isolated storage
posted by: winphonegeek on 3/25/2011 1:18:25 PM
Actually both :
1.A directory must be empty before it is deleted because DeleteDirectory fails if the directory contains any files or subdirectories. (you can not delete a folder that isn't empty).
2.The deleted directory cannot be recovered once deleted.
As to the problem you mentioned we were unable to reproduce this behavior. You could share some more code here or send it to support@windowsphonegeek.com, so that we will be able to reproduce and fix the issue.
Can I mark a file to be part of IsolatedStorage during design time
posted by: Usman ur Rehman Ahmed on 5/20/2011 8:59:24 AM
This may be ridiculous but is there a way that I can mark a file (.txt for example) during design time (within visual studio solution explorer) to be part of the Isolated Storage of the application and read it during execution?
Disposable
posted by: Shawn Wildermuth on 7/13/2011 2:25:25 AM
Looks like all your examples are missing that the files and data store are all Disposable and you're not cleaning them. While on the desktop you can assume that some of this will be cleaned up by the OS if you do the wrong thing, it's pretty bad on the phone. A couple of using statements go a long way to helping make this stuff cleaner for google-driven-development people.
In addition, sharing the IsolatedStorageFile is pretty key as opening the store is a somewhat expensive operation.
MoveFile
posted by: TopView on 9/29/2011 11:06:23 AM
I see the method MoveFile() in the .Net Framework 4.0, but i can't see it in visual studio 2010 ? can anybody tell me why ?
How to know a path is a file or a folder ?
posted by: Halley on 11/10/2011 4:21:15 AM
Seems no way to tell file from folder according to a path ? and CreateDirectoryAll("folder1/folder2/folder3/folder4") function is also absent now,we need to create folder level by level(folder1->folder1/folder2->folder1/folder2/folder3->...).
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
