.NET Streams
The Stream base class is an abstraction of a sequence of bytes. A stream may be sequential or random access. .NET defines several derived stream classes, not all of which reside in System.IO. Stream implements IDisposable.
Stream overview
Stream presents properties to determine whether a stream CanRead, CanWrite, CanSeek or CanTimeout. Streams that support seeking implement the Position and Length properties.
Stream presents virtual methods to sequentially read and write (Read, ReadByte, Write, WriteByte), as well as Flush, Seek, SetLength and Close.
This example illustrates how to write and read to a file, using the static File class to create the required FileStreams.
const string path = @"C:\file.txt"; using (FileStream fs = File.Create(path)) { byte[] info = new UTF8Encoding(true).GetBytes("some text to write"); fs.Write(info, 0, info.Length); } using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read)) { byte[] b = new byte[1024]; UTF8Encoding encoding = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { Console.WriteLine(encoding.GetString(b)); } } |
You could repeat the above example, but substitute the FileStream for a MemoryStream.
MemoryStream ms = new MemoryStream(); |
MemoryStream also provides the facility to write to another stream, like so:
MemoryStream ms = new MemoryStream(); // write some data to ms FileStream fs = File.Create(@"C:\mem.txt"); ms.WriteTo(fs); fs.Close(); ms.Close(); |
In order to improve performance, BufferedStream adds a buffering layer to read and write operations on another stream. For example:
FileStream fs = File.Create(@"C:\buffered.txt"); BufferedStream bs = new BufferedStream(fs); // write data to bs like any other stream |
Compressed streams
The System.IO.Compression namespace provides the GZipStream and DeflateStream classes. Both use the same compression algorithm (which does not depend on any patents). GZipStream writes data with headers that allow the data to be decompressed with GZip, and therefore has a slightly larger footprint.
Compressed streams may be used in a similar fashion to buffering:
FileStream destination = new FileStream(@"C:\compressed.txt"); // when writing to gzipStream, we compress data then write it to the destination stream GZipStream gzipStream = new GZipStream(destination, CompressionMode.Compress); byte[] buffer = new byte[256]; // put some data in the buffer gzipStream.Write(buffer); |
Decompression is essentially the same, except you perform reads instead of writes.