- What Is Isolated Storage?
- Using Isolated Storage
- Persisting Application Settings
- Security Considerations
Using Isolated Storage
The isolated storage API is fully contained in the System.IO.IsolatedStorage namespace. Objects within the namespace allow you to create and access stores and files. The two objects within that namespace that you'll use most often are IsolatedStorageFile and IsolatedStorageFileStream.
Before you can read from or write to isolated storage, you must first create an instance of IsolatedStorageFile. This object represents a directory (folder) on the hard drive in which individual isolated storage streams are stored. After you have obtained a store (an IsolatedStorageFile object), you can create IsolatedStorageFileStream objects on that store in which you can store data. IsolatedStorageFileStream is a class that derives from FileStream, which gives you a familiar interface to the data in isolated storage.
Listing 1 shows a simple console mode program that illustrates how to open an isolated storage file, create a stream, write data to the stream, and read it back.
Listing 1 isostore.cs
using System; using System.IO; using System.IO.IsolatedStorage; namespace isostore { class Class1 { private static string StreamName = "MyData.txt"; [STAThread] static void Main(string[] args) { Console.WriteLine("Isolated storage example"); IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForDomain(); try { // write data to the stream IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream( StreamName, FileMode.OpenOrCreate, FileAccess.Write, isoFile); try { StreamWriter writer = new StreamWriter(isoStream); try { writer.WriteLine("Hello, isolated storage."); } finally { writer.Close(); } } finally { isoStream.Close(); } // read data back from the stream isoStream = new IsolatedStorageFileStream(StreamName, FileMode.Open, FileAccess.Read, isoFile); try { StreamReader reader = new StreamReader(isoStream); try { string s = reader.ReadLine(); Console.WriteLine("Read data: ", s); } finally { reader.Close(); } } finally { isoStream.Close(); } } finally { isoFile.Close(); } } } }
This code isolates the data by user, domain, and assembly. If you want to isolate by user and assembly, replace the call to GetUserStoreByDomain with a call to GetUserStoreByAssembly.
The IsolatedStorageFile class has methods that allow you to create and remove directories; and delete, rename, and otherwise manipulate individual streams in the store. Refer to the .NET documentation for a full description of the methods and properties of this class.