Input/Output Classes in C#

Introduction

In memory, objects cease to exist when a program ends. But files exist until deletion. With files we persist data. A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically a sequence of bytes passing through the communication path. There are two main streams, the input stream and the output stream.

The input stream is used for reading data from a file (read operation) and the output stream is used for writing into the file (write operation). We handle them with types in System.IO.

Various Types of C# I/O Classes

The System.IO namespace has various classes for performing various operation with files, like creating and deleting files, reading from or writing to a file, closing a file and so on.

Some important classes are as follows:

I/O Class Description
FileStream Used to read from and write to any location in a file
BinaryReader Reads primitive data from a binary stream
BinaryWriter Writes primitive data in binary format
File Use for manipulating files
StreamReader Used for reading characters from a byte stream
StreamWriter Is used for writing characters to a stream
StringReader Is used for reading from a string buffer
StringWriter Is used for writing into a string buffer
Directory Helps in manipulating a directory structure
DirectoryInfo Used for performing operations on directories

Now we see examples of some important I/O class and examine the outputs.

The FileStream Class

The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows:

  1. FileStream <object_name> = new FileStream( <file_name>,<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);  
For example, create a FileStream object F for reading a file named Example.txt as:
  1. FileStream My_File = new FileStream("Example.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);  
Now we see the meaning of each parameter.

FileMode

The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
 
Mode Description
Append It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist
Create It creates a new file. If file is already exist then it will overrite that file
CreateNew It will also use to create a new file If the file is already exist then it will throw an Exception
Open It opens an existing file
OpenOrCreate It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file
Truncate It opens an existing file and truncates its size to zero bytes

FileAccess

The FileAccess enumerator defines the kind of task to do with the file.

AccessMode Description
Read Data can be write from file
Write Data can be write written to the file
ReadWrite Data can be written to and read from the file

FileShare

This enumerator applies the type of permission for sharing.

SharingMode Description
Inheritable It allows a file handle to pass inheritance to the child processes
None It declines sharing of the current file
Read It allows opening the file for reading
ReadWrite It allows opening the file for reading and writing
Write It allows opening the file for writing

Example

The following program shows the use of the FileStream class:



Stream Reader and Stream Writer

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream that supports reading and writing bytes into a file stream.

The StreamReader Class

The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class:

Method Name Description
public override void Close() It closes the StreamReader object and the underlying stream and releases any system resources associated with the reader.
public override int Peek() Returns the next available character but does not consume it
public override int Read() Reads the next character from the input stream and advances the character position by one character

The StreamWriter Class

The StreamWriter class inherits from the abstract class TextWriter that represents a writer that can write a series of characters.

The following table shows some of the most commonly used methods of this class:

Method Description
public override void Close() Closes the current StreamWriter object and the underlying stream
public override void Flush() Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream
public virtual void Write(bool value) Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)
public override void Write( char value ) Writes a character to the stream
public virtual void Write( decimal value ) Writes the text representation of a decimal value to the text string or stream
public virtual void Write( double value ) Writes the text representation of an 8-byte floating-point value to the text string or stream
public virtual void Write( int value ) Writes the text representation of a 4-byte signed integer to the text string or stream
public override void Write( string value ) Writes a string to the stream
public virtual void WriteLine() Writes a line terminator to the text string or stream

Example

The following example shows writing text data into a file using the StreamWriter class:



Binary Reader and Binary Writer

The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.

The BinaryReader Class

The BinaryReader class is used to read binary data from a file. A BinaryReader object is created by passing a FileStream object to its constructor.
The following table shows some of the commonly used methods of the BinaryReader class:

Method Description
public override void Close() It closes the BinaryReader object and the underlying stream
public virtual int Read() Reads the characters from the underlying stream and advances the current position of the stream
public virtual bool ReadBoolean() Reads a Boolean value from the current stream and advances the current position of the stream by one byte
public virtual char ReadChar() Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream
public virtual char[] ReadChars( int count ) Reads the specified number of characters from the current stream, returns the data in a character array and advances the current position in accordance with the Encoding used and the specific character being read from the stream
public virtual string ReadString() Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time

The BinaryWriter Class

The BinaryWriter class writes binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.

The following table shows some of the commonly used methods of the BinaryWriter class:

Method Description
public override void Close() It closes the BinaryWriter object and the underlying stream
public virtual long Seek( int offset, SeekOrigin origin ) Sets the position within the current stream
public virtual void Write( byte[] buffer ) Writes a byte array to the underlying stream
public virtual void Write( char ch ) Writes a Unicode character to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream
public virtual void Write( char[] chars ) Writes a character array to the current stream and advances the current position of the stream in accordance with the Encoding used and the specific characters being written to the stream
public virtual void Write( string value ) Writes a length-prefixed string to this stream in the current encoding of the BinaryWriter and advances the current position of the stream in accordance with the encoding used and the specific characters being written to the stream

Example 1



Example 2

Let us see another example that will clarify the concepts.

  1. static void Main(string[] args)  
  2. {  
  3.     string FILE_NAME = "Test_File.data";  
  4.     // Create the new, empty data file.  
  5.     if (File.Exists(FILE_NAME))  
  6.     {  
  7.         Console.WriteLine("{0} is already exists!", FILE_NAME);  
  8.         Console.WriteLine("Please Give Another Name");  
  9.         return;  
  10.     }  
  11.     using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))  
  12.     {  
  13.         // Create the writer for data.  
  14.         using (BinaryWriter w = new BinaryWriter(fs))  
  15.         {  
  16.             // Write data to Test.data.  
  17.             for (int i = 0; i < 20; i++)  
  18.             {  
  19.                 w.Write(i);  
  20.             }  
  21.         }  
  22.     }  
  23.     // Create the reader for data.  
  24.     using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))  
  25.     {  
  26.         using (BinaryReader r = new BinaryReader(fs))  
  27.         {  
  28.             // Read data from Test.data.  
  29.             for (int i = 0; i < 20; i++)  
  30.             {  
  31.                 Console.WriteLine(r.ReadInt32());  
  32.             }  
  33.         }  
  34.   
  35.         Console.ReadKey();  
  36. }  
Output



I hope this article help you learn about File I/O in C#. 


Recommended Free Ebook
Similar Articles