Sunday, August 16, 2009

Creating Isolated Storage Files

Introduction

Many programmers use the config file to keep the application configuration data. But one disadvantage with this is, it is a read only mechanism. You cannot update data in application config files, using the ConfigurationSettings classes in .NET. In earlier days, .ini files or registry was used to save application specific data.

Of course, we can use regular files to save application data. But now the question is how to protect the data, where to save it and all other mess!

Isolated Storage

.NET introduces a concept called Isolated Storage. Isolated Storage is a kind of virtual folder. Users never need to know where exactly the file is stored. All you do is, tell the .NET framework to store your file in Isolated Storage. The physical location of Isolated Storage varies for each Operating System. But your application simply uses the .NET classes to create and access files, without bothering where it is physically located. And you can have Isolated Storage specific to each Assembly or each Windows user.

The following code sample demonstrates the basic create, write and read operations with Isolated Storage.

Make sure you include the following directives on top of your file:

using System.IO;
using System.IO.IsolatedStorage;
using System.Diagnostics;
public static void Main(string[] args)
{
const string ISOLATED_FILE_NAME = "MyIsolatedFile.txt";

//-------------------------------------------------------


// Check if the file already exists in isolated storage.


//-------------------------------------------------------


IsolatedStorageFile isoStore =
IsolatedStorageFile.GetStore( IsolatedStorageScope.User
| IsolatedStorageScope.Assembly, null, null );

string[] fileNames = isoStore.GetFileNames( ISOLATED_FILE_NAME );

foreach ( string file in fileNames )
{
if ( file == ISOLATED_FILE_NAME )
{
Debug.WriteLine("The file already exists!");
}
}

//-------------------------------------------------------


// Write some text into the file in isolated storage.


//-------------------------------------------------------


IsolatedStorageFileStream oStream =
new IsolatedStorageFileStream( ISOLATED_FILE_NAME,
FileMode.Create, isoStore );

StreamWriter writer = new StreamWriter( oStream );
writer.WriteLine( "This is my first line in the isolated storage file." );
writer.WriteLine( "This is second line." );
writer.Close();

//-------------------------------------------------------


// Read all lines from the file in isolated storage.


//-------------------------------------------------------


IsolatedStorageFileStream iStream =
new IsolatedStorageFileStream( ISOLATED_FILE_NAME,
FileMode.Open, isoStore );

StreamReader reader = new StreamReader( iStream );
String line;

while ( (line = reader.ReadLine()) != null )
{
Debug.WriteLine( line );
}

reader.Close();
}

No comments: