Sherman Quick

Another one of those .NET Nerds...
posts - 10, comments - 2, trackbacks - 5

Thursday, April 12, 2007

Use of Isolated Storage in .NET 2.0

Wouldn't it be nice if there was a way for your Windows application to store information on the local hard drive without having to worry about user access privileges?  Well, with .NET 2.0, there is and the classes associated with it are IsolatedStorageFile and IsolatedStorageFileStream.   Long story short is that use of these classes will allow your Windows app to cache information on the local hard drive specific to your assembly or application even if your user has the lowest of the low account privilege (i.e. restricted access like Limited or Guest). 

 

In my code sample below, I'm going to use the above mentioned classes to perform the following actions for a console application (i.e. assembly):

  1. Store information on the hard drive specific to the user of the console application
  2. Retrieve that information for use at a later time

 

Here is the code you can use to do this:

// Be sure you add these two namespaces...

using System.IO;
using System.IO.IsolatedStorage;

...

// Write info to isolated storage based on the user and assembly...

IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly();

IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.set",
FileMode.Create, userStore);

StreamWriter stream = new StreamWriter(userStream);

// Info you want to save...
stream.WriteLine("Saved Info: Whatever you want");
stream.Close();

...

// Read info from isolated storage...

string[] file = userStore.GetFileNames("UserSettings.set");
if (file.Length != 0)
{
userStream = new IsolatedStorageFileStream("UserSettings.set",
FileMode.Open, userStore);
StreamReader reader= new StreamReader(userStream);
string contents = reader.ReadToEnd();

// Write the info to the console... 
Console.WriteLine(contents);
}

As you can see, this is a super simple and easy to use method for saving application info to the hard drive without having to worry about user access privileges.

posted @ Thursday, April 12, 2007 6:56 PM | Feedback (0)

Powered by: