Streams are used for transferring data from your application to an external source or to transfer data from an external source to your application. Streams provide a way to read and write bytes to and from a back store, which could be a file, memory, or another source.
There are many types of streams that you can choose. Table 11-4 describes the main stream classes provided by .NET that you can use in C#.
|
Stream Type |
Description |
|---|---|
|
System.IO.MemoryStream |
A stream that uses memory for backing |
|
System.Net.Sockets.NetworkStream |
A stream used for network transmission |
|
BufferedStream |
A stream that reads and writes using buffers |
|
FileStream |
A stream used to read and write to a binary file |
|
CryptoStream |
A stream that links data streams to cryptographic transformations |
All the .NET classes that represent streams inherit from the base class of System.IO.Stream. Table 11-5 describes the common stream reader and writer classes. All stream classes provide the following methods and properties: Read, Write, Seek, CanRead, CanWrite, and CanSeek. They also have the Flush and Close methods. The Flush method is important because it pushes the stream from memory to the actual back store. The Close method calls Flush.
|
Class |
Description |
|---|---|
|
StringReader / StringWriter |
Used like sprintf to modify strings into different types |
|
StreamReader / StreamWriter |
Allows you to read and write to and from a text file |
|
TextReader / TextWriter |
Provides character input and output |
|
BinaryReader / BinaryWriter |
Reads and writes primitive types as binary values in a specific encoding to and from a stream |
The following examples demonstrate the use of FileStream, StreamReader, StreamWriter, and StringReader. The final example shows the use of the BinaryFormatter class, which allows you to serialize and deserialize a stream into binary format. The example shows a simple solution that takes a class and serializes it to binary format inside a file.
using System; using System.IO; namespace Client.Chapter_11___Files_and_Streams { public class UsingFileStreams { static void Main(string[] args) { //Creates a file with read-write access //that allows others to read. FileStream MyFileStream1 = new FileStream(@"c:\Projects\Testing.txt", FileMode.Create); FileInfo MyFiles = new FileInfo(@"c:\Projects\Testing.txt"); FileStream MyFileStream2 = MyFiles.OpenRead(); //Or any of the following MyFileStream2 = MyFiles.OpenWrite(); MyFileStream2 = MyFiles.Open(FileMode.Append, FileAccess.Read, FileShare.None); MyFileStream2 = MyFiles.Create(); //You can read file streams on a per-byte //basis or as an array of bytes. int MyBytes = MyFileStream1.ReadByte(); //Or int NumberOfBytes = 200; byte[] MyByteArray = new Byte[NumberOfBytes]; int BytesRead = MyFileStream1.Read(MyByteArray, 0, NumberOfBytes); //Data can be written to FileStreams as well through bytes //or arrays of bytes. byte MyWriteByte = 100; MyFileStream1.WriteByte(MyWriteByte); //Or via an array int NumberOfBytesToWrite = 256; byte[] MyWriteByteArray = new Byte[NumberOfBytesToWrite]; for (int i = 0; i < 256; i++) { MyWriteByteArray[i] = (byte)i; i++; } MyFileStream1.Write(MyWriteByteArray, 0, NumberOfBytesToWrite); MyFileStream1.Close(); MyFileStream2.Close(); } } }
using System; using System.IO; namespace Client.Chapter_11___Files_and_Streams { public class StreamReaderAndWriter { static void Main(string[] args) { StreamReader MyStreamReader = new StreamReader(@"c:\Projects\Testing.txt"); //If you need to control share permissions when //creating a file, use FileStream with StreamReader. FileStream MyFileStream = new FileStream(@"c:\Projects\Testing.txt", FileMode.Open, FileAccess.Read, FileShare.None); StreamReader MyStreamReader2 = new StreamReader(MyFileStream); MyFileStream.Close(); MyStreamReader2.Close(); //The easiest way to read a stream is to //use the ReadLine method. //This method reads until it gets to the end of a line, but //it does not copy the carriage return line feed /n/r. string MyStringReader = MyStreamReader.ReadLine(); //You can also read the whole file by using the following. string MyStringReadToEOF = MyStreamReader.ReadToEnd(); //The other route is to read one character at a time. int[] MyArrayOfCharacters = new int[100]; for (int i = 0; i < 99; i++) { MyArrayOfCharacters[i] = MyStreamReader.Read(); } MyStreamReader.Close(); } } }
using System; using System.IO; namespace Client.Chapter_11___Files_and_Streams { public class UsingStreamWriter { static void Main(string[] args) { //StreamWriter can be used only to write //to files or other streams. StreamWriter MyStreamWriter = new StreamWriter(@"c:\Projects\Testing.txt"); //You can also use FileStream with StreamWriter //to provide a greater degree of control //in how the file is opened. FileStream MyFileStream = new FileStream(@"c:\Projects\Testing.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None); StreamWriter MyStreamWriter2 = new StreamWriter(MyFileStream); MyFileStream.Close(); MyStreamWriter2.Close(); //You can write sequentially to a file using this technique. FileInfo MyFile = new FileInfo(@"c:\Projects\Testing.txt"); StreamWriter MyStreamWriter3 = MyFile.CreateText(); MyStreamWriter3.Close(); //There are four overloaded ways to use StreamWriter.Write(). //Writes a stream to a file string MyString = "Hello World"; MyStreamWriter.Write(MyString); //Writes single characters to a stream char MyChar = 'A'; MyStreamWriter.Write(MyChar); //Writes an array of characters char[] MyCharArray = new char[100]; for (int i = 0; i < 99; i++) { MyCharArray[i] = (char)i; } MyStreamWriter.Write(MyCharArray); //Or you can write a portion of an array MyStreamWriter.Write(MyCharArray, 25, 30); MyStreamWriter.Close(); } } }
using System; using System.IO; namespace Client.Chapter_11___Files_and_Streams { public class UsingStringReader { static void Main(string[] args) { //Create a string to read characters from. String MyString = "Hello World"; //Size the array to hold all the characters of the string, //so that they are all accessible. char[] MyChar = new char[12]; //Create a StringReader and attach it to the string. StringReader MyStringReader = new StringReader(MyString); //Read 5 characters from the array that holds //the string, starting from the first array member. MyStringReader.Read(MyChar, 0, 5); //Display the output. Console.WriteLine(MyChar); //Close the StringReader. MyStringReader.Close(); } } }
using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace Client.Chapter_11___Files_and_Streams { class Class1 { [STAThread] static void Main(string[] args) { Point p1 = new Point(); p1.xpoint = 0x1111; p1.ypoint = 0x2222; //Opens a file and serializes the object into it. Stream stream = File.Open("onepoint.bin", FileMode.Create); BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(stream, p1); stream.Close(); //Read the data from a file and deserialize it. Stream openStream = File.Open("onepoint.bin", FileMode.Open); Point deserializedPoint = new Point(); deserializedPoint = (Point)bformatter.Deserialize(openStream); } } [Serializable()] class Point { public int xpoint; public int ypoint; } }