19.1 Implementing the File Input and Output Operations
Programs accept input from the user, process the input and produces an output. All the languages support input and output operations. The file is a collection of data stored on a disk with the specific name and directory path. The file open for reading and writing data is known as stream.
The stream is a sequence of bytes from source to destination through the communication path. The two basic streams are the input and output streams. Every stream has a function associated with it. The input stream is used for read operation and output stream is used for a write operation.
The System.IO namespace contains various classes, used for performing operations as file creation, file deletion, read – write operations.
The following table is used to describe the classes in the System.IO namespace.
Class Name | Description |
FileStream | It is used to read and write from any location within a file |
BinaryReader | It is used to read primitive data types from a binary stream |
BinaryWriter | It is used to write primitive data types in a binary format to a binary stream |
StreamReader | It is used to read characters from a byte stream |
StreamWriter | It is used to write characters to a stream |
StringReader | It is used to read from a string buffer |
StringWriter | It is used to write into a string buffer |
DirectoryInfo | It is used to perform operations on directions |
FileInfo | It is used to perform operations on files |
FileStream Class
The file input/output operations is implemented in the System.IO namespace. User can use the FileStream class in the System.IO namespace to read, write, and close files. These classes are inherited from an abstract class called Stream.
The following syntax is used to create an object of the FileStream class:
FileStream <objectname> = new FileStream ( <file name>, <file Mode Enumerator>,
<File Access Enumerator> , <FileShare Enumerator> );
The code snippet for creating an object of the FileStream class is as shown below:
FileStream fs = new FileStream ( “data.txt”, FileMode.Open. FileAccess.Read, FileShare.Read);
In the code snippet, the FileMode, FileAccess and FileShare enumerators define constants used by the FileStream class.
FileMode Enumerator
The FileMode Enumerator defines methods for opening files. It is used to restrict the mode in which the file is opened by the user. The parameters to the enumerator check if the file is overwritten created or opened.
The members of the enumerator are as follows:
1) Append: It opens the file if it exists and places the cursor at the end of the file or creates a new file.
2) Create: It creates a new file
3) CreateNew: It specifies to an operating system that a new file should be created
4) Open: It opens an existing file
5) OpenOrCreate: It specifies to the system that open a file if it exists, else create a new file
6) Truncate: It opens an existing file. When opened, the file should be truncated, the size of the file is zero bytes
File Access Enumerator
The file is opened for both reading and writing operations. The enumerator is used to indicate whether user wants to read data from a file, write data to the file or perform both operations.
The members of the enumerator are Read, Write and ReadWrite.
FileShare Enumerator
The enumerator contains constants for controlling the access that the FileStream constructors have on the file. The use of the enumeration is to define whether two different applications can simultaneously read from the same file.
The members of the FileShare enumerator are as follows:
1) Inheritable: It allows a file handle to pass the inheritance to the child processes
2) None: It rejects sharing of the current file
3) Read: It allows the opening of a file for reading purpose
4) ReadWrite: It allows opening a file for the purpose of reading and writing
5) Write: It allows the opening of a file for writing
19.2 Implementing Reading and Writing in the Text Files
The Stream class is used to read data and write data to the text files. The StreamReader and StreamWriter class are used to read and write data in the files.
StreamReader Class
The StreamReader class is inherited from the abstract class as TextReader. The class represents a reader used for reading a series of characters.
The following table is used to represent the methods used in the StreamReader class
Methods | Description |
Close | It closes the object of the StreamReader class and stream, and releases system resources associated with the reader |
Peek | It returns the next available character but does not consume it |
Read | It reads the next character or the next set of characters from the stream |
ReadLine | It reads a line of characters from the current stream and returns data as a string |
Seek | It allows the read/write position to be moved to any position within the file |
The following code is used to implement the StreamReader class to read data from a file
class Program { public void ReadData() { FileStream fs = new FileStream("E:\\data.txt", FileMode.Open, FileAcess.Read); StreamReader sr = newStreamReader ( fs ); sr.BaseStream.Seek( 0, SeekOrigin.Begin); string str = sr.ReadLine(); while ( str ! = null ) { Console.WriteLine("{0}", str ); str = sr.ReadLine(); } sr.Close(); fr.Close(); } static void Main ( string[ ] args ) { Program p = new Program(); p.ReadData(); Console.Read(); } }
The output for the code is as shown below
:
In the above code, the FileMode property value is used to Open and FileAccess property value is Read. The file data.txt is in open mode and prepares the stream for read operation. The reader statement creates a new instance of the StreamReader class for the text file.
The Seek() method allows the read position to be moved to the beginning of the file and read till the end of the file.
StreamWriter Class
The StreamWriter class is inherited from the abstract class called TextWriter. The class represents a writer, which can write a series of characters.
The following table describes the methods of the StreamWriter class.
Methods | Description |
Close | It closes the current object and the stream |
Flush | It clears all buffers for the current writer and causes any buffered data to be written to the stream |
Write | It writes to the stream |
WriteLine | IT writes data specified by the overloaded parameters, followed by the end of line |
The following code implements the StreamWriter class to accept data from the user and write it into the file.
class Program { public void WriteData() { FileStream fs = new FileStream(“E://data.txt”, FileMode.Append, FileAccess.Write); StreamWriter w = new StreamWriter(fs); Console.WriteLine(“Enter the string”)l string str = Console.ReadLine(); w.Write(str); w.Flush(); fs.Close(); } static void Main ( string[ ] args ) { Program p = new Program(); p.WriteData(); Console.Read(); } }
The output for the code is as shown below:
The text file name data contains the string. The file is as shown below:
In the above code, The FileMode property value is Append and the FileAccess property value is Write. The file data.txt is opened in the append mode and the stream is used for the write operation. A new instance of the StreamWriter class is created.
The Flush() method clears the stream buffer. The Close() method closes the stream and releases the resources associated with the stream.
19.3 Implementing Reading and Writing in Binary Files
The information stored in the text format would be displayed on the screen as text. Reading an:d writing data in the binary format means the number is written as float consuming four bytes of space. The BinaryReader and BinaryWriter classes are used for reading and writing binary data in files.
BinaryReader Class
The BinaryReader class is used to read binary data from a file. The BinaryReader object is passed to the FileStream object to the constructor. The code snippet is as shown below:
The following table shows the methods of the BinaryReader class.
Method | Description |
Close | It closes the current reader and stream |
Read | It reads the characters from the stream and moves to the current position of the stream |
BinaryWriter Class
The BinaryWriter class is used to write binary data to a stream. User can create BinaryWriter object by passing the FileStream object to the constructor.
The following table shows the methods used by the BinaryWriter class.
Method | Description |
Close | It closes the current BinaryWriter object and stream |
Seek | It sets the position within the current stream |
Write | It writes the value to the current stream |
Flush | It clears the buffer for the current writer and the buffered data is written to the device |
The following code is used for implementing the BinaryReader and BinaryWriter classes to read and write data to the files.
class Program { static void Main ( string[ ] args ) { BinaryReader datain; BinaryWriter dataout; int i=20; double j = 101.50; bool b = true; dataout = new BinaryWriter( new FileStream ( “data”, FielMode.Create ) ); Console.WriteLine(“Writing is”+ i ); dataout.Write ( i ); Console.WriteLine(“Writing is”+ j); dataout.Write ( j ); Console.WriteLine(“Writing is”+ b ); dataout.Write ( b ); Console.WriteLine( “Writing” + 12.2 * 15.5 ); dataout. Write( 12.2 * 15.5 ); dataout.Close(); Console.WriteLine(); datain = new BinaryReader ( new FileStream ( “data”, FileMode.Open ) ); i = datain.ReadInt32(); Console.WriteLine( “Reading” + i ); j = datain.ReadDouble(); Console.WriteLine( “Reading” + j ); b = datain.ReadBoolean(); Console.WriteLine( “Reading” + b ); j = datain.ReadDouble(); Console.WriteLine( “Reading” + j ); Console.Read(); datain.Close(); } }
The output for the code is as shown below
:
19.4 Implementing the Windows File System
It is necessary for the user to locate the files and directories. The FileInfo and DirectoryInfo classes are used for gathering information about files and directories at the specified location.
DirectoryInfo Class
The DirectoryInfo class is derived from the FileSystemInfo class. The following table shows some of the properties of the DirectoryInfo class.
Property | Description |
Attributes | It gets or sets attributes of the current file. It is an inherited property from FileSystemInfo class. |
CreationTime | It gets or sets the creation time of the file. |
Exists | It gets a Boolean value indicating whether the directory exists or not. |
Extension | It gets a string containing the file extension. |
FullName | It gets a string containing full path of the directory. |
LastAccessTime | It gets the last accessed time of the directory. |
Name | It gets a string containing the name of a given file. |
The following table describes the commonly used methods of the DirectoryInfo class.
Method | Description |
Create | It creates a directory. |
CreateSubDirectory | It creates a subdirectory. |
Delete | It deleted a directory. |
GetDirectories | It returns the directories in the current directory after all the criteria are matched. |
GetFiles | It returns the files in the current directory. |
The code snippet for creating the DirectoryInfo object is as shown below:
class Program { static void Main ( string[ ] args ) { DirectoryInfo dirinfo = new DirectoryInfo ( @”C:\\Windows”); Console.WriteLine(“Full Name of the directory is : {0}”, dirinfo.FullName ); Console.WriteLine(“The directory was last accesses on: {0}”, dirinfo.LastAccessTime.ToString() ); Console.Read(); } }
The output for the code is as shown below:
In the above snippet, the object of DirectoryInfo is created. It displays the full name and last time when it was accessed.
FileInfo Class
The FileInfo class is derived from the FileSystemInfo class. The following table contains the properties of the FileInfo class.
Property | Description |
Attributes | It gets or sets the attributes associated with the current file. |
CreationTime | It gets or sets the creation time of the current file. |
Directory | It gets an instance of the directory to which it belongs. |
Exists | It gets a Boolean value indicating whether a file exists or not. |
Extension | It gets a string containing file extension. |
FullName | It gets a string containing full path of the file. |
LastAccessTime | It gets the last accessed time of the file. |
LastWriteTime | It gets the time of last written activity to the file. |
Length | It gets the size of the file. |
Name | It gets a string containing the name of a given file. |
The following table shows the methods of the FileInfo class.
Method | Description |
Create | It creates a file. |
AppendText | It appends a text to the file represented by the FileInfo object. |
Delete | It deletes a file |
Open | It opens file. |
OpenRead | It opens a file in read – only mode. |
The code snippet demonstrating the FileInfo class is a shown below:
class Program { static void Main ( string[ ] args ) { DirectoryInfo dirinfo = new DirectoryInfo ( @”C:\\Windows”); FileInfo[ ] FileInDir = dirinfo.GetFiles(); foreach ( FileInfo file in FileDir ) { Console.WriteLine(“File Name {0} Size: {1} bytes”, filename, file.Length ); } Console.Read(); } }
The output for the code is as shown below:
In the above code, the GetFiles() method is used to retrieve the list of all the files in the directory. It displays the list of all the files in the directory along with their sizes.