Wednesday, January 23, 2008

Streams 2

There are other useful stream and reader/writer classes.

For working with strings, we can use StringReader and StringWriter. Also, remember the StringBuilder class, but the last one isn't an stream.

TextReader and TextWriter are abstract base class that StreamReader, StreamWriter, StringReader, and StringWriter derive from.

For binary tasks, we can use BinaryReader and BinaryWriter. Here another approach for reading compressed binary files:

// Open the stream we want to decompress
FileStream fs = File.OpenRead(@"c:\temp\filename.zip");
 
// Creates the GZipStream
GZipStream gzip = new GZipStream(fs, CompressionMode.Decompress);
 
// We want to read binary content into one memory stream
// This could be also a FileStream object
MemoryStream ms = new MemoryStream();
 
// We use the binary reader for improve the performance
BinaryReader br = new BinaryReader(gzip);
 
byte[] b = br.ReadBytes(1000);
while (b.Length > 0)
{
    ms.Write(b, 0, b.Length);
    b = br.ReadBytes(1000);
}
 
// Show read content's length
MessageBox.Show(ms.Length.ToString());
ms.Close(); // Close our target stream
 
br.Close(); // This also closes the GZipStream and the FileStream (the underlying stream)*/

0 comments:


View My Stats