WindowsDevCenter.com
oreilly.comSafari Books Online.Conferences.

advertisement


AddThis Social Bookmark Button

C# Input/Output Classes Simplified
Pages: 1, 2, 3, 4, 5

The FileStream Class

The FileStream class represents a stream that wraps a file. You use FileStream for reading and writing bytes of a file. The FileStream class uses buffering to improve performance. The easiest way to construct a FileStream object is to use one of its constructors, which accepts a file path and a value from the FileMode enumeration as arguments. For instance, the following code creates a file called newFile.txt and writes two bytes into it. If the file already exists, the file will be overwritten:


FileStream fs = new FileStream("C:/newFile.txt", 
     FileMode.Create);
Byte[] bytes = new Byte[2];
bytes[0] = 65;
bytes[1] = 66;
fs.Write(bytes, 0, 2);
fs.Close();

Some methods return a FileStream object without requiring that you create it with one of its constructors. For example, the following code uses the File class' Create method to create a file called newFile.txt, returns a FileStream object, and then writes two bytes to the file:


FileStream fs = File.Create("C:/newFile2.txt");
Byte[] bytes = new Byte[2];
bytes[0] = 65;
bytes[1] = 66;
fs.Write(bytes, 0, 2);
fs.Close();

If you want to append to a file instead of creating a new one, you must use the FileStream constructor that accepts a FileMode and a FileAccess value, and you must specify FileAccess. Write for the file access type, as shown in the following code:


FileStream fs = new FileStream("C:/newFile.txt", 
     FileMode.Append, FileAccess.Write);

To read from a file, you can use FileMode. Open as the file mode argument in one of the FileStream class' constructors. The following code, for instance, reads two bytes from the newFile.txt file:


FileStream fs = new FileStream("C:/newFile.txt", 
     FileMode.Open);
Byte[] bytes = new Byte[2];
int i = fs.Read(bytes, 0, 2);
fs.Close ();

The BufferedStream Class

The BufferedStream class is used to wrap a Stream object and supports buffering to improve performance. There are two constructors that you can use to create a BufferedStream object. The first one accepts a Stream object. The BufferedStream object constructed using this constructor has a buffer size of 4,096 bytes. The second constructor accepts a Stream object as well as an Integer specifying the size of the buffer, allowing you to set your own buffer size.

As an example of how to use the BufferedStream, consider the following code, which wraps the Stream object returned from an OpenFileDialog in a BufferedStream object and reads the first 128 bytes of the selected file:


    OpenFileDialog openFileDialog = new OpenFileDialog();
      if (openFileDialog.ShowDialog() == DialogResult.OK) 
      {
        string filepath = openFileDialog.FileName;
        // Open the file using the OpenFile method
        BufferedStream bufferedStream = new BufferedStream(
		     openFileDialog.OpenFile());
        Byte[] bytes = new Byte[128];
        bufferedStream.Read(bytes, 0, 128);
      }

Note that the BufferedStream class is derived from the Stream class; therefore, it inherits all of the Stream class' methods and properties.

The StreamReader Class

The StreamReader class is a child class of TextReader. You use StreamReader and other Reader classes to manipulate text. With this class, you can use the Read method to read one character each time or a fixed number of characters, or you can use the ReadLine method to read a line of text. You can construct a StreamReader object from a Stream object returned by a method call, or by specifying a path to a file to one of the StreamReader class constructors.

Optionally, you can also pass an encoding scheme to a constructor to tell the StreamReader object the encoding used in the text file. If no encoding is supplied, the default encoding (System.Text.UTF8Encoding) is assumed. The stream's current encoding can be retrieved from the read-only CurrentEncoding property.

As an example, the following code opens a text file named CompanySecret.txt and uses the ReadLine method to print the text to the Debug window one line at a time. The ReadLine method returns a null reference if it encounters the end of the stream:


    StreamReader sr = new StreamReader("
	     C:/CompanySecret.txt");
      string line = sr.ReadLine();
      while (line != null) 
      {
        System.Console.WriteLine(line);
        line = sr.ReadLine();
      }
      
      sr.Close();

Note that when you read a line of text using the ReadLine method, the end-of-line character is not included in the returned String.

The StreamWriter Class

The StreamWriter class is derived from the TextWriter class and can be used to write text to a stream. You can create an instance of the StreamWriter class by assigning it a Stream object returned by a method call, or by passing a file path to one of its constructors. Like the StreamReader class, you can also pass an encoding scheme of your choice to one of its constructors. The most important methods of the StreamWriter class are Write and WriteLine. Write enables you to write a character, an array of characters, or a string. The WriteLine method accepts a String and adds an end-of-line character to the end of the string. For example, the following code opens a new file called NewCompanySecret.txt and writes a string of text to it:


StreamWriter sw = new StreamWriter("
     C:/NewCompanySecret.txt");
string line = "Don't tell anyone!!!";
sw.WriteLine(line);
sw.Close();

The BinaryReader Class

You use the BinaryReader class to read binary data from a file. You can construct a BinaryReader object by passing its constructor a Stream object; you can't pass a file path to create a BinaryReader object. Once you have a BinaryReader object, you can use one of its ReadXXX methods to read various types of data. For example, the ReadByte method is used to read a byte, and the ReadString method is used to read a String. The data must be read in the order it was written. For example, if you store a byte and then a string to a binary file, you must first read a byte and then read a String. The BinaryReader class also has a Read method, which has three overloads that allow you to read a character, an array of bytes, or an array of characters. As an example, here is the code that reads a byte and a string from a binary file called MyBinary.bin:


BinaryReader br = new BinaryReader(File.OpenRead("
     C:/MyBinary.bin"));
Byte b2 = br.ReadByte();
string s2 = br.ReadString();
System.Console.WriteLine(s2);
System.Console.WriteLine(b2);
br.Close();

The BinaryWriter Class

The BinaryWriter class is used to write binary data to a stream. You can construct a BinaryWriter object by passing a Stream object; you can’t pass a file path to create a BinaryWriter object. In addition, there is also a parameterless constructor. The BinaryWriter class’ most important method is Write. This method has 18 overloads that guarantee that you can write any type of data to a BinaryWriter object. For example, the following code creates a BinaryWriter object that is linked to a new file called MyBinary.bin, and writes a byte and a string:


BinaryWriter bw = new BinaryWriter(File.Create("
     C:/MyBinary.bin"));
Byte b = 17;
string s = "August";
bw.Write(b);
bw.Write(s);
bw.Close();

Budi Kurniawan is a senior J2EE architect and author.


Return to .NET DevCenter