Wednesday, January 23, 2008

Working with IsolatedStorage class

Creating a file in our isolated store:
// Create our isolated store with Machine/Assembly scope
// Also, we can create one with User/Assembly scope and others.
IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForAssembly();
 
// Open our stream for writing to it
IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("filename.txt", FileMode.Create, isf);
 
// Using StreamWriter to write
StreamWriter sw = new StreamWriter(isfs);
sw.WriteLine("test line");
 
sw.Flush();
sw.Close(); // Close the stream
 
isf.Close();
The isolated store will be created on C:\Documents and Settings\All Users\Application Data\IsolatedStorage\..\..\..\AssemFiles. Reading files from our isolated store:
// Create our isolated store with Machine/Assembly scope
IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForAssembly();
 
// Open our stream for reading from it
IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("filename.txt", FileMode.Open, isf);
 
// Using StreamReader to read
StreamReader sr = new StreamReader(isfs);
MessageBox.Show(sr.ReadToEnd());
 
sr.Close(); // Close the stream
 
isf.Close();
Using directories:
// Create our isolated store with Machine/Assembly scope
IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForAssembly();
 
// Create one directory
isf.CreateDirectory("Temp");
 
// Open our stream for writing to it
IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(@"Temp\filename.txt", FileMode.Create, isf);
 
// Using StreamWriter to write
StreamWriter sw = new StreamWriter(isfs);
sw.WriteLine("another line");
 
sw.Flush();
sw.Close();  // Close the stream
 
isf.Close();
Also, we can remove our isolated store:
// Create our IsolatedStorage with Machine/Assembly scope
IsolatedStorageFile isf = IsolatedStorageFile.GetMachineStoreForAssembly();
 
// Removing our isolated store
isf.Remove();
Other useful methods: GetFileNames GetDirectoryNames DeleteDirectory DeleteFile

0 comments:


View My Stats