Isolated Storage is a slick little feature available to Microsoft .Net Windows applications and services. It allows a VB.Net or C#.Net assembly to persist some piece of information to a protected location on disk. This information can be a serialized object, a string, a date, or whatever. I use Isolated Storage fairly regularly in Services to store progress information or startup information. I usually keep startup/configuration information in the database but frequently the services must be able to start even when the database is not available. I first attempt to retrieve the information from the database and if unable, read the last good data from Isolated Storage. When the database access is successful, I write the current information to Isolated Storage so the most recent data is always available.
You will need to import/use the .Net System.IO and .Net System.IO.IsolatedStorage namespaces.
The following code will write the data to a location to which only the current user or assembly has permission:
Dim _isolatedStorageStore As IsolatedStorageFile _isolatedStorageStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User Or IsolatedStorageScope.Assembly, Nothing, Nothing) Dim _streamWriter As New StreamWriter( New IsolatedStorageFileStream("File/Store Name", FileMode.OpenOrCreate, _isolatedStorageStore)) _streamWriter.WriteLine(lString) _streamWriter.Close()
Reading the contents of the file is just the reverse:
Dim _isolatedStorageStore As IsolatedStorageFile _isolatedStorageStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User Or IsolatedStorageScope.Assembly, Nothing, Nothing) Dim _streamReader As New StreamReader( New IsolatedStorageFileStream("File/Store Name", FileMode.Open, _isolatedStorageStore)) Dim _fileContents As String _fileContents = _streamReader.ReadLine _streamReader.Close()
Note that reading the contents back can be more complicated depending on what you have written into the file. You may need to use something other than the StreamReader ReadLine routine to retrieve the full contents.
The following code will delete the file that you have created:
_isolatedStorageStore.DeleteFile("File/Store Name")
There are many, many uses for Isolated storage. Storing a user’s preferences, last selection, history, etc… are all possibilities.
Leave a Reply