Objectives In this chapter, you will learn to: =| Implement the file input and output operations =] Implement read and write in text files =] Implement read and write in binary files =]
Trang 1This chapter introduces the concept of the file input and output operations It explains the process of reading and writing in the text files and the binary files It also explains the process of browsing through the Windows File System
Objectives
In this chapter, you will learn to:
=| Implement the file input and output operations
=] Implement read and write in text files
=] Implement read and write in binary files
=] Implement the Windows File System
Trang 3Implementing the File Input and Output Operations
All programs accept input from a user, process the input, and produce an output
Therefore, all the programming languages support the input and output operations For information to be saved permanently on a disk, you can use a file The file is a collection
of data stored on a disk with a specific name and very often with a directory path When you open the file for reading data or writing data, it becomes a stream
The stream is a sequence of bytes travelling from a source to a destination over a
communication path The two basic streams used are the input and output streams Each stream has a particular function An input stream is used for a read operation and an output stream is used for performing a write operation You can perform both these
operations over the stream
The System 10 namespace includes various classes, which are used to perform
operations, such as file creation, file deletion, and the read-write operations to files
The following table describes some commonly used classes in the System ¡1O namespace
Class Name Description
FileStream Is used to read from and write to any location within a file BinaryReader Is used to read primitive data types from a binary stream
BinaryWriter Is used to write primitive data types in binary format
StreamReader Is used to read characters from a byte stream
StreamWriter Is used to write characters to a stream
StringReader Is used to read from a string buffer
String Writer Is used to write into a string buffer
DirectoryInfo Is used to perform operations on directories
FileInfo Is used to perform operations on files
Common Class of System 10 Namespace
In NET, you can work with streams by using the FileStream class This class supports random access to files, which means to read from and write to any location within a file
Trang 4FileStream Class
Most file Input/Output (I/O) support 1n the NET Framework is implemented in the System 10 namespace You can use the FileStream class in the System 10 namespace to read from, to write, and to close files This class inherits from the abstract class stream Many of its properties and methods are also derived from the Stream class
To open an existing file or to create a new file, you need to create an object of type FileStream Consider the following syntax for creating the object of type FileStream:
FileStream <object name>=new FileStream(<file Name>,<FileMode
Enumerator>,<File Access Enumerator>,<FileShare Enumerator>);
Consider the following example for creating the object of type FileStream:
FileStream Filel= new FileStream (“Myfile.txt”’, FileMode.Open,
FileMode Enumerator
This enumerator defines various methods for opening files The FileMode enumerator parameter is specified in many constructors for the FileStream,
IsolatedStorageFileStream constructors, and in the open methods of File and
FileInfo to restrict how a file is opened The parameters to FileMode checks whether a
file is overwritten, created, or opened
The members of the FileMode enumerator are:
Append: Opens the file if it exists and places the cursor at the end of file, or creates
a new file
Create: Creates a new file
CreateNew: Specifies to an operating system that is should create a new file
Open: Opens an existing file
OpenOrCreate: Specifies to the operating system that it should open a file if it
exists; otherwise, it should create a new file
Truncate: Opens an existing file When opened, the file should be truncated so that its size 1s zero bytes
Trang 5FileAccess Enumerator
Unless you specify a FileAccess enumerator, the file gets opened for both reading and writing This enumerator indicates whether you want to read data from the file, write to the file, or perform both the operations
The members of the FileAccess enumerator are Read, ReadWrite, and Write
The members of the FileShare enumerator are:
w Inheritable: Allows a file handle to pass inheritance to the child processes
w® None: Declines sharing of a current file
w Read: Allows opening ofa file for reading purpose
® ReadWrite: Allows opening a file for the purpose of reading and writing
® Write: Allows opening of a file for writing purpose
Trang 6Implementing Reading and Writing in the Text Files
The Stream Class is used to read from and to write data in the text files It is an abstract class, which supports reading and writing bytes into it If data of a file is only text, then you can use the St reamReader class and the StreamWriter class to accomplish the
reading and writing tasks, respectively
StreamReader Class
The St reamReader class is inherited from the abstract class TextReader The
TextReader class represents a reader which can read a series of characters
The following code implements the St reamReader class:
FileStream fs = new FileStream("Myfile.txt",
FileMode.Open, FileAccess.Read) ;
StreamReader sr = new StreamReader (fs);
sr.BaseStream Seek(0, SeekOrigin.Begin);
string str = sr.ReadLine();
In the preceding code, the Seek () method allows the read/write position to be moved to any position within the file This method takes two parameters, a byte position and a reference point The byte position is relative to the reference point The reference point can be Begin, Current, or End These reference points are represented by the properties
of the SeekOrigin class
The reference point, Begin, provides the seek reference position as the beginning of the stream Current provides the seek reference position as the current position within the stream and the reference point End, provides the seek reference position as the end of the stream The objects of the FileStream class are used to provide random access to files The FileStream constructor takes parameters that are used to initialize the members of the class
Trang 7The following table describes some of the commonly used methods of the st reamReader
class
Methods Description
Close Closes the object of StreamReader class and the underlying stream,
and releases any system resources associated with the reader Peek Returns the next available character but does not consume it
Read Reads the next character or the next set of characters from the stream
ReadLine Reads a line of characters from the current stream and returns data as
a string
Seek Allows the read/write position to be moved to any position within the
file
Methods of the St reamReader Class
The following code snippet implements the StreamReader class to read data from the file:
StreamReader sr = new StreamReader(fs);
//Position the file pointer at the beginning of the file sr.BaseStream.Seek (0, SeekOrigin.Begin);
//Read till the end of the file is encountered
string str = sr.ReadLine();
while (str != null) {
fr.ReadData();
Trang 8In addition, code reads from Myfile.txt The Seek() method allows the read position to
be moved to the beginning of a file and read till the end of the file
StreamWriter Class
The Stream riter class is inherited from the abstract class TextWriter The
TextWriter class represents a writer, which can write a series of characters
The following table describes some of the commonly used methods of the St reamWriter
Close Closes the current StreamWriter object and the underlying stream
Flush Clears all buffers for the current writer and causes any buffered data to
be written to the underlying stream Write Writes to the stream
WriteLine Writes data specified by the overloaded parameters, followed by end of
line
Methods of the St reamWriter Class
The following code implements the StreamWriter class to accept data from a user and write the same into the file:
using System;
using System.10;
class FileWrite
{ public void WriteData() {
//object of filestream class is created
FileStream fs = new FileStream("Myfile.txt", FileMode.Append,
FileAccess.Write);
StreamWriter w = new StreamWriter(fs);
Trang 9// Prompting user to enter the string which needs to be stored in //the file
FileWrite fw = new FileWrite();
fw WriteData();
}
In the preceding code, the Fi 1eMode property value is Append and the FileAccess property value is Write This opens the file, Myfile.txt, in the append mode and
prepares the stream for a write operation The statement, StreamWriter w=new
StreamWriter (fs), creates a new instance of the StreamWriter class for Myfile txt
In addition, code accepts input from a user and writes the contents to Myfile.txt The functions that can be used for the write operations are Write () and WriteLine() The difference between Write() and WriteLine() operations is that the write () method is used to display the specified information on the output destination while the
WriteLine() method is used to display the information followed by a line terminator
The Flush() method clears the stream buffer The close () method closes the stream and
releases any resources associated with the current stream
Trang 10Implementing Reading and Writing in Binary Files
All the information stored in the text format would be displayed on a screen as text This means 'A' will be written as 'A' in the files Similarly, the number —12345.678 will be written as the string "-12345.678" This means that you can directly display the contents
of the file on the screen
Binary read and write means that the number —12345.678 is written as a float
representation consuming four bytes of space The BinaryReader and BinaryWriter classes are used for reading and writing the binary data in to files
BinaryReader Class
The BinaryReader class is used to read binary data from a file You can create
BinaryReader object by passing its constructor, a FileStream object, as shown in the following code snippet:
FileStream fs = new
FileStream(@"C:\TEST2.DAT", FileMode Open, FileAccess.Read) ;
BinaryReader br = new BinaryReader(fs);
The following table describes some of the commonly used methods of the BinaryReader
class
Method Description
Close Closes the current reader and the underlying stream
Read Reads characters from the underlying stream and advances the current
position of the stream
Methods for the BinaryReader Class
BinaryWriter Class
The BinaryWriter class is used to write binary data to a stream You can create a
BinaryWriter object by passing its constructor, a FileStream object, as shown in the following code snippet:
FileStream fs = new
FileStream(@"C:\TEST2.DAT", FileMode.CreateNew) ;
BinaryWriter bw = new BinaryWriter(fs);
Trang 11The following table describes some ofthe commonly used methods of the Bi nazyWzitez
class
Method Description
Close Closes the current BinaryWriter and the underlying stream
Seek Sets the position within the current stream
Write Writes a value to the current stream
Flush Clears all buffers for the current writer and causes any
buffered data to be written to the underlying device
Method of the BinarywWriter Class
The following code snippet shows the implementation of the Binary Reading and Binary Writing classes to a file:
Console.WriteLine ("Writing "+ i):
Trang 13The following window shows the output of preceding code snippet
cx file: ///C:/DataFiles/BinaryData/Binar yData/bin/Debug/BinaryData EXE
Output of the Binary Reading Application
Trang 14Implementing the Windows File System
The ability to browse and locate files and directories for a specific directory 1s essential for many programming tasks You can work with files and directories by using classes such as the DirectoryInfo and FileInfo classes in combination Using these classes is
an efficient way to gather the required information about files and directories in a specific location
DirectoryInfo Class
The DirectoryInfo class 1s derived from the FileSystemiInfo class The following table describes some of the commonly used properties of the Di rectoryInfo class
Property Description
Attributes Gets or sets attributes associated with the current file This
property is inherited from FileSystemInfo
_ Gets or sets CreationTime of the current file This property is
CreationTime inherited from FileSystemInfo ý J properly
Exists Gets a Boolean value indicating whether the directory exist or not Gets a string containing the file extension This property is
inherited from FileSystemInfo
FullName Gets a string containing the full path of the directory This property
is inherited from FileSystemInfo
Gets the last accessed time of the directory This property is LastAccessTime inherited from FileSystemInfo ý ở properly
Name Gets a string containing the name of a given file
Properties of the DirectoryInfo Class