15. File Handling Notes
15. File Handling Notes
What is a File?
So, in simple words, we can say that a stream is a sequence of bytes that is
used for communication. When you open a file for reading or writing, it
becomes a stream. There are two types of streams for a single file. One is the
Input stream which is used for reading the file and the other one is the Output
stream which is used for writing the file.
WHY I NEED TO LEARN FILE HANDLING?
Generally, we use the file to store data. The term File Handling in C# refers to
the various operations that we can perform on a file such as creating a file,
reading data from the file, writing data into the file, appending the file, etc.
1. Reading: This operation is the basic read operation where the data is
going to be read from a file.
2. Writing: This operation is the basic write operation where the data is
going to be written to a file. By default, all existing contents are
removed from the file, and new content is written in the file.
3. Appending: This operation is the same as the write operation where the
data is going to be written to a file. The only difference between Write
and Append is that the existing data in the file will not be overwritten.
With Append, the new data is going to be added at the end of the file.
One more thing that you need to remember the file becomes a stream when
we open the file either for writing or for reading.
System.IO Namespace in C#
Note: The File Info, Directory Info, and Drive Info classes have instance
methods. File, Directory, and Path classes have static methods.
CLASSES
Class Description
If you go to the definition of FileStream class, then you will see that there are
many overloaded versions of Constructors available as shown in the below
image.
FileMode
– It specifies how to operation system should open the file. If you go to the
definition of FileMode, then you will see that it is an Enum with the following
structure and It has following members .
a) Append - Open the file if exist or create a new file. If file exists then
place cursor at the end of the file.
b) Create - It specifies operating system to create a new file. If file already
exists then previous file will be overwritten.
c) CreateNew - It create a new file and If file already exists then throw
IOException.
d) Open – Open existing file.
e) Open or Create – Open existing file and if file not found then create
new file.
f) Truncate – Open an existing file and cut all the stored data. So the file
size becomes 0.
FileAccess
Methods:
1) Close(): This method closes the current StreamWriter object and the
underlying stream.
2) Flush(): This method Clears data from all buffers for the current writer
and causes any buffered data to be written to the underlying stream.
3) Write(): It Writes data to the stream. It has different overloads for
different data types to write in the stream.
4) WriteLine: It is the same as Write() but it adds the newline character at
the end of the data. It has different overloads for different data types
to write in the stream.
5) Dispose(): It releases the unmanaged resources used by the
StreamWriter and optionally releases the managed resources.
Properties:
StreamReader Class in C#
If you go to the definition of StreamReader class then you will see the
following. The StreamReader class belongs to the System.IO namespace and
implements the abstract TextReader class. The StreamReader class in C# is
used for reading characters from the stream in a particular format.
Constructor:
It initializes a new instance of the StreamReader class for the specified stream
or string path based on the specified character encoding, byte order mark
detection option, and buffer size, and optionally leaves the stream open. It
has different overloaded versions which you can see in the above image.
Methods:
1) Close(): The Close method Closes the StreamReader object and the
underlying stream, and releases any system resources associated with
the reader.
2) Peek(): This method returns the next available character but does not
consume it. An integer represents the next character to be read, or -1 if
there are no characters to be read or if the stream does not support
seeking.
3) Read(): This method reads the next character from the input stream
and advances the character’s position by one character. The next
character from the input stream is represented as a System.Int32
object, or -1 if no more characters are available.
4) ReadLine(): This method Reads a line of characters from the current
stream and returns the data as a string. The next line from the input
stream, or null if the end of the input stream is reached.
5) Seek(): It is used to read/write at a specific location from a file.
6) Properties:
7) CurrentEncoding: It gets the current character encoding that the
current System.IO.StreamReader object is using.
8) EndOfStream: It gets a value that indicates whether the current stream
position is at the end of the stream.
9) BaseStream: It returns the underlying stream.
As discussed, it is very easy to read a text file using StreamReader Class in C#.
we are doing the following thing:
Write some data on a text file using StreamWriter Class
Read those data using the StreamReader Class.
File Class in C#
The File Class in C# Provides some static methods to perform most file
operations, such as Creating a File, Copying and Moving a File, Deleting Files,
and working with FileStream to read and write streams. The File class is
defined in the System.IO namespace. There can be situations where you
want to work with files directly. The basic file operations that we generally do
are as follows:
The File class in C# exposes many static methods for moving, copying,
reading, writing, and deleting files. The File belongs to the System.IO
namespace; if you go to the definition of the File class, you will see the
following.
File Class Methods in C#:
The following are commonly used methods of File class in C#.
The static Create Method of File Class in C# creates a file in the specified
folder or directory. There are multiple overloaded versions of this method
available in the File class. They are as follows:
The TextReader and TextWriter classes in C# are another way to read and
write files respectively, even though these are not stream classes. The
TextReader and TextWriter are base classes. The StreamReader and
StringReader derive from the abstract type TextReader. Similarly, the
StreamWriter and StringWriter derive from the abstract type TextWriter.
What is TextWriter Class in C#?
The TextWriter class in C# represents a writer that can write sequential series
of characters. We can use this TextWriter class to write text in a file. It is an
abstract base class of StreamWriter and StringWriter, which write characters
to streams and strings respectively. It is used to write text or sequential series
of characters into files. It is found in the System.IO namespace. If you go to
the definition of TextWriter Class, you will see that it is an abstract class as
shown in the below image.
Points to Remember:
The BinaryWriter class in C# is used to write Primitive type data types such as
int, uint, or char in the form of binary data to a stream. It is present under the
System.IO namespace. As its name says BinaryWriter writes binary files that
use a specific data layout for its bytes.
If you have a binary file (with .bin extension) stored in your machine
and if you want to read the binary data then you need to use the
BinaryReader class in C#. That means the BinaryReader class in C# is
used to reading binary file data. A binary file stores data in a different
layout that is more efficient for machines but not convenient for
humans. BinaryReader makes this job simpler and shows you the exact
data stored in the binary file.
The BinaryReader class belongs to the System.IO namespace.
BinaryReader is used to read primitive data types as binary values in a
particular encoding stream. BinaryReader works with Stream object i.e.
in order to create an object of BinaryReader, we need to pass the
Stream object to its constructor. BinaryReader class has three
overloaded constructors to work with binary data. By default,
BinaryReader uses UTF-8 encoding to read data until we specify other
character encodings while creating its object.
1) The BinaryReader class in C# handles Binary (.bin) files.
2) It reads primitive data types as binary values in a specific encoding.
3) The BinaryReader class provides methods that simplify reading primitive
data types from streams.
The StringWriter Class in C# is derived from the TextWriter class and this
StringWriter class is mainly used to manipulate strings rather than files.
The StringWriter class enables us to write a string either synchronously or
asynchronously. So, we can write a character either with Write(Char) or
WriteAsync(Char) method and we can write a string with Write(String)
or WriterAsync(String) method. The text or information written by
StringWriter class is stored inside a StringBuilder. The Text namespace
and the strings can be built efficiently using the StringBuilder class
because strings are immutable in C# and the Write and WriteLine
methods provided by StringWriter help us to write into the object of
StringBuilder. StringBuilder class stores the information written by
StringWriter class.
The most important point that you need to remember is that the
StringWriter is not for writing files on the local disk. It is used for
manipulating strings and it saves information in StringBuilder. If you go
to the definition of StringWriter class, then you will see the following.
Constructors of StringWriter in C#
Encoding: This property is used to get the Encoding in which the output
is written. So, it returns the Encoding in which the output is written.
Methods of StringWriter Class in C#
The StringWriter Class in C# provides the following methods.
1) Close(): This method is used to close the current StringWriter and the
underlying stream.
2) Dispose(): This method is used to release the unmanaged resources
used by the System.IO.StringWriter and optionally releases the
managed resources.
3) FlushAsync(): This method is used to asynchronously clear all buffers for
the current writer and causes any buffered data to be written to the
underlying device.
4) GetStringBuilder(): This method is used to return the underlying
StringBuilder.
5) ToString(): This method is used to return a string containing the
characters written to the current StringWriter so far.
6) Write(char value): This method is used to write a character to the string.
7) Write(string value): This method is used to write a string to the current
string.
8) WriteAsync(char value): This method is used to write a character to the
string asynchronously.
9) WriteAsync(string value): This method is used to write a string to the
current string asynchronously.
10)WriteLine(String): This method is used to Write a string followed by a line
terminator to the text string or stream.
11)WriteLineAsync(string value): This method is used to write a string
followed by a line terminator asynchronously to the current string.
What is StringReader Class in C#?