Compression and Isolated Storage
In this post we’ll examine the topics of compressing data, and the usage of the Isolated Storage feature of the .NET Framework. The namespaces are System.IO.Compression and System.IO.IsolatedStorage.
That’s an easy one, you’ll need to know two classes and an enumeration, namely: GZipStream, DeflateStream and CompressionMode. Even better GzipStream and DeflateStream can be used in the exact same way. The main difference, as you’d guess is the compression method. Both classes derives from Stream, so you can call the Read, Write and Seek methods. Both of them provides two constructors: the first one accepts a stream and a member of the CompressionMode enumeration. The second extends the first with a Boolean that indicates whether or not the stream should be kept open.
To compress a file into another one:
GZipStream zip = new GZipStream(File.Create(“my.zip”), CompressionMode.Compress);
StreamWriter sw = new StreamWriter(zip);
FileStream fs = File.Open(“myFileToCompress.doc”);
StreamReader sr = new StreamReader(fs);
To decompress, use a similar syntax, but use CompressionMode.Decompress instead.
Using the Isolated Storage, you can store data that cannot be accessed by less trusted code. You can define isolated storage sites for a given assembly, a given domain, or a user. To start working with isolated storage, you should create an instance of IsolatedStorageFile class by calling one of the static methods of it:
Then pass this instance into the constructor of an IsolatedStorageFileStream class. An example:
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fs = new IsolatedStorageFileStream(“myFile.txt”, FileMode.Create, file);
Then you can treat the IsolatedStorageFileStream as if it were a normal FileStream (since it extends it).