0% found this document useful (0 votes)
7 views

15. File Handling Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

15. File Handling Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

 File Handling in C#

What is a File?

A file is a collection of data stored on a disk with a specific name, extension,


and directory path. When you open File using C# for reading and writing
purposes it becomes Stream.
What is Stream?

A stream is a sequence of bytes travelling from a source to a destination over


a communication path. There are two main streams: The Input Stream and
the Output Stream. The input stream is used for reading data from the file
(read operation) and the output stream is used for writing into the file (write
operation).
Input Stream: This Stream is used to read data from a file, which is known as a
read operation.
Output Stream: This Stream is used to write data into a file, which is known as
a write operation.

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?

As a C# Programmer, we need to save information on a disk. We will not get


a database everywhere to save the information and our project may require
saving information in a TEXT file, DOC file, XLS file, PDF file, or any other file
type. So, we must know the concept of saving data in a file i.e. How to
Handle Files in C#.
File Handling in C#

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.

Generally, we mostly perform three basic operations on a file: reading data


from a file, writing data to a file and appending data to a file.

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#

In C#, The System.IO namespace contains the required classes used to


handle the input and output streams and provide information about file and
directory structure. The parent class of file processing is Stream. Stream is an
abstract class used as the parent of the classes that implement the necessary
operations.

Note: The File Info, Directory Info, and Drive Info classes have instance
methods. File, Directory, and Path classes have static methods.
CLASSES
Class Description

1) BinaryReader Reads primitive data types as binary values in a


specific encoding.
2) BinaryWriter Writes primitive types in binary to a stream and supports
writing strings in a specific encoding.
3) BufferedStream Adds a buffering layer to read and write operations
on another stream. This class cannot be inherited.
4) Directory Exposes static methods for creating, moving, and
enumerating through directories and subdirectories. This class cannot
be inherited.To browse the .NET Framework source code for this type,
see the Reference Source.
5) DirectoryInfo Exposes instance methods for creating, moving, and
enumerating through directories and subdirectories. This class cannot
be inherited.To browse the .NET Framework source code for this type,
see the Reference Source.
6) DirectoryNotFoundException The exception that is thrown when part
of a file or directory cannot be found.
7) DriveInfo Provides access to information on a drive.
8) DriveNotFoundException The exception that is thrown when trying to
access a drive or share that is not available.
9) EndOfStreamException The exception that is thrown when reading is
attempted past the end of a stream.
10)ErrorEventArgs Provides data for the FileSystemWatcher.Error event.
11)File Provides static methods for the creation, copying, deletion,
moving, and opening of a single file, and aids in the creation of
FileStream objects.To browse the .NET Framework source code for this
type, see the Reference Source.
12)FileFormatException The exception that is thrown when an input file
or a data stream that is supposed to conform to a certain file format
specification is malformed.
13)FileInfo Provides properties and instance methods for the creation,
copying, deletion, moving, and opening of files, and aids in the
creation of FileStream objects. This class cannot be inherited.To browse
the .NET Framework source code for this type, see the Reference
Source.
14)FileLoadException The exception that is thrown when a managed
assembly is found but cannot be loaded.
15)FileNotFoundException The exception that is thrown when an attempt
to access a file that does not exist on disk fails.
16)FileStream Provides a Stream for a file, supporting both synchronous
and asynchronous read and write operations.To browse the .NET
Framework source code for this type, see the Reference Source.
17)FileSystemEventArgs Provides data for the directory events:
Changed, Created, Deleted.
18)FileSystemInfo Provides the base class for both FileInfo and
DirectoryInfo objects.
19)FileSystemWatcher Listens to the file system change notifications
and raises events when a directory, or file in a directory, changes.To
browse the .NET Framework source code for this type, see the
Reference Source.
20)InternalBufferOverflowException The exception thrown when the
internal buffer overflows.
21)InvalidDataException The exception that is thrown when a data
stream is in an invalid format.
22)IODescriptionAttribute Sets the description visual designers can
display when referencing an event, extender, or property.
23)IOException The exception that is thrown when an I/O error occurs.
24)MemoryStream Creates a stream whose backing store is memory.To
browse the .NET Framework source code for this type, see the
Reference Source.
25)Path Performs operations on String instances that contain file or
directory path information. These operations are performed in a cross-
platform manner.To browse the .NET Framework source code for this
type, see the Reference Source.
26)PathTooLongException The exception that is thrown when a path or
file name is longer than the system-defined maximum length.
27)PipeException Thrown when an error occurs within a named pipe.
28)RenamedEventArgs Provides data for the Renamed event.
29)Stream Provides a generic view of a sequence of bytes. This is an
abstract class.To browse the .NET Framework source code for this type,
see the Reference Source.
30)StreamReader Implements a TextReader that reads characters from
a byte stream in a particular encoding.To browse the .NET Framework
source code for this type, see the Reference Source.
31)StreamWriter Implements a TextWriter for writing characters to a
stream in a particular encoding.To browse the .NET Framework source
code for this type, see the Reference Source.
32)StringReader Implements a TextReader that reads from a string.
33)StringWriter Implements a TextWriter for writing information to a string.
The information is stored in an underlyingStringBuilder.
34)TextReader Represents a reader that can read a sequential series of
characters.
35)TextWriter Represents a writer that can write a sequential series of
characters. This class is abstract.
36)UnmanagedMemoryAccessor Provides random access to unmanaged
blocks of memory from managed code.
37)UnmanagedMemoryStream Provides access to unmanaged blocks
of memory from managed code.

 What is FileStream Class

The FileStream Class in C# provides a stream for file operations. It can be


used to perform both Synchronous and Asynchronous Read and Write
operations. With the help of FileStream Class, we can easily read and write
data into files.
HOW TO USE FILESTREAM CLASS IN C#?

In order to use FileStream class you need to include System.IO namespace


and then create FileStream Object to create a new file or open an existing
file.
 FileStream <object_name> = new FileStream( <file_name>, <FileMode
Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);

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

– It gives permission to file whether it will open Read, ReadWrite or Write


mode. FileShare – It opens file with following share permission. If you go to the
definition of FileAccess, then you will see that it is an Enum with the following
structure.
a) Delete – Allows subsequent deleting of a file.
b) Inheritable – It passes inheritance to child process.
c) None – It declines sharing of the current files.
d) Read- It allows subsequent opening of the file for reading.
e) ReadWrite – It allows subsequent opening of the file for reading or
writing.
f) Write – Allows subsequent opening of the file for writing.

 StreamReader and StreamWriter in C#


StreamWriter Class in C#

The StreamWriter Class in C# is more popular in File Handling and it is very


helpful in writing text data into a file. It is easy to use and provides a complete
set of constructors and methods to work on it. StreamWriter class in C# is used
for writing characters to stream in a particular format. If you go to the
definition of StreamWriter class then you will see the following. The
StreamWriter Class in C# belongs to the System.IO namespace and
implements the abstract TextWriter class.
Constructor:

The Constructor is used to initialize a new instance of the


System.IO.StreamWriter class for the specified file on the specified path,
Specified Stream, specified encoding and buffer size. It has also different
overloaded versions for different ways to create an instance of StreamWriter
Class.

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:

1) AutoFlush: Gets or sets a value indicating whether the StreamWriter will


flush its buffer to the underlying stream after every call to
System.IO.StreamWriter.Write(System.Char).
2) BaseStream: Gets the underlying stream that interfaces with a backing
store.
3) Encoding: Gets the System.Text.Encoding in which the output is written.

StreamReader Class in C#

The StreamReader class in C# allows us to read text files. Its implementation is


easy and it is widely popular among developers. However, there are many
ways to read text files in C# but StreamReader Class is more popular in the
list. While working with C# StreamReader Class, you need to remember the
following points.

1. Implements a TextReader that reads characters from a byte stream in


a particular encoding.
2. StreamReader class uses UTF-8 Encoding by default.
3. StreamReader class is designed for character input in a particular
encoding.
4. Use this class for reading a standard text file.
5. By default, it is not thread-safe.

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.

Using both StreamReader and StreamWriter Class in C#

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:

1. Reading: This operation is the basic Read Operation wherein data is


read from a file.
2. Writing: This operation is the basic Write Operation wherein data is
written to a file. All existing contents are removed from the file by
default, and new content is written.
3. Appending: This operation also involves writing information to a file. The
only difference is that the existing data in a file is not overwritten. The
new data to be written is added at the end of the file.

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#.

1) Copy: This method is used to Copy an existing file to a new file.


Overwriting a file of the same name is not allowed.
2) Create: This method creates or overwrites it in the specified path.
3) Decrypt: This method is used to Decrypt a file encrypted by the current
account using the System.IO.File.Encrypt(System.String) method.
4) Delete: This method is used to delete the specified file.
5) Encrypt: This method is used to encrypt a file so that only the account
used to encrypt the file can decrypt it.
6) Open: This method is used to Open a System.IO.FileStream on the
specified path, having the specified mode with reading, write, or
read/write access and the specified sharing option.
7) Move: This method is used to Move a specified file to a new location,
providing the option to specify a new file name.
8) Exists: This method is used to determine whether the specified file exists.
9) OpenRead: This method is used to open an existing file for reading.
10)OpenText: This method opens an existing UTF-8 encoded text file for
reading.
11)OpenWrite: This method is used to open an existing file or create a new
file for writing.
12)ReadAllBytes: This method is used to open a binary file, read the file’s
contents into a byte array, and then close the file.
13)ReadAllLines: This method is used to Open a file, read all lines of the file
with the specified encoding, and then close the file.
14)ReadAllText: This method is used to Open a text file, read all the text in
the file, and then close the file.
15)ReadLines: This method is used to read the lines of a file.
16)Replace: This method is used to replace a specified file’s contents with
another file’s contents, delete the original file, and create a backup of
the replaced file.
17)WriteAllBytes: This method is used to create a new file, write the
specified byte array to the file, and then close the file. If the target file
already exists, it is overwritten.
18)WriteAllLines: This method is used to create a new file, write the
specified string array to the file, and then close the file.
19)WriteAllText: This method is used to create a new file, write the specified
string to the file, and then close the file. If the target file already exists, it
is overwritten.

Create Method 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:

1. public static FileStream Create(string path): Creates or overwrites a file


in the specified path.
2. public static FileStream Create(string path, int bufferSize): Creates or
overwrites the specified file. The bufferSize parameter specifies the
number of bytes buffered for reads and writes to the file.
3. public static FileStream Create(string path, int bufferSize, FileOptions
options): Creates or overwrites the specified file, specifying a buffer size
and a FileOptions value that describes how to create or overwrite the
file.
4. public static FileStream Create(string path, int bufferSize, FileOptions
options, FileSecurity fileSecurity): Creates or overwrites the specified file
with the specified buffer size, file options, and file security.

Note: All the above-overloaded versions return an instance of the FileStream


class. So, we need to close the stream object by calling the Close method.
TextWriter and TextReader in C#
TextWriter and TextReader Classes in C#:

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.

Methods of TextWriter class in C#:

1. Synchronized(TextWriter): It is used to Create a thread-safe wrapper


around the specified TextWriter.
2. Close(): It Closes the current writer and releases any system resources
associated with the writer.
3. Dispose(): It releases all resources used by the System.IO.TextWriter
object.
4. Flush(): It Clears all buffers for the current writer and causes any
buffered data to be written to the underlying device.
5. Write(Char): It is used to write a character to the text stream.
6. Write(String): It is used to write the string to the text stream.
7. WriteAsync(Char): It is used to write the character to the text stream
asynchronously.
8. WriteLine(): It is used to write a line terminator to the text stream.
9. WriteLineAsync(String): It is used to write the string to the text stream
asynchronously followed by a line terminator.
Note: There are many overloaded versions of Write and WriteAsync methods
available in TextWriter class.

Points to Remember:

1. TextWriter is an abstract class belonging to the System.IO namespace.


2. It is used to write a sequential series of characters into a file.
3. It is the base class of StreamWriter and StringWriter which is used to
write characters to streams and strings respectively.
4. By default, it is not thread-safe.
5. As it is an abstract class, its object cannot be created. Any class
implementing TextWriter must minimally implement its Write(Char)
method to create its useful instance.

What is TextReader class in C#?

The TextReader class in C# represents a reader that is used to read text or


sequential series of characters from a text file. TextReader class belongs to
the System.IO namespace. It is an abstract class which means you cannot
instantiate it. It is an abstract base class of StreamReader and StringReader
which are used to read characters from stream and string respectively.

Methods of TextReader Class in C#:

1. Synchronized(): It is used to create a thread-safe wrapper around the


specified TextReader.
2. Close(): It is used to close the TextReader and release any system
resources associated with the TextReader.
3. Dispose(): It is used to release all resources used by the TextReader
object.
4. Peek(): It is used to read the next character without changing the state
of the reader or the character source. Returns the next available
character without actually reading it from the reader. It returns an
integer representing the next character to be read, or -1 if no more
characters are available or the reader does not support seeking.
5. Read(): It is used to read the next character from the text reader and
advances the character’s position by one character. It returns the next
character from the text reader, or -1 if no more characters are
available. The default implementation returns -1.
6. ReadLine(): It is used to read a line of characters from the text reader
and returns the data as a string. It returns the next line from the reader,
or null if all characters have been read.
7. ReadToEnd(): It is used to read all characters from the current position
to the end of the text reader and returns them as one string. That
means it reruns a string that contains all characters from the current
position to the end of the text reader.

BinaryWriter and BinaryReader in C#


What is BinaryWriter Class in C#?

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.

1. The BinaryWriter in C# creates a binary file that is not human-


understandable but the machine can understand it.
2. It supports writing strings in a specific encoding.
3. In order to create an object of BinaryWriter, we need to pass an object
of Stream to the constructor of the BinaryWriter class.
4. The BinaryWriter class in C# provides methods that simplify writing
primitive data types to a stream.
5. If you don’t provide types of encoding while creating objects then
default encoding UTF-8 will be used.
Methods of BinaryWriter Class in C#:

1. Write(String): This method is used to write 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.
2. Write(float): This method is used to write a four-byte floating-point value
to the current stream and advances the stream position by four bytes.
3. Write(long): This method is used to write an eight-byte signed integer to
the current stream and advances the stream position by eight bytes.
4. Write(Boolean): This method is used to write the one-byte Boolean
value to the present stream; 0 represents false while 1 represents true.
5. Write(Byte): This method is used to write an unsigned byte to the
present stream and then it advances the position of the stream by one
byte.
6. Write(Char): This method is used to write Unicode characters to the
present stream and also it advances the present stream position
according to the character encoding used and according to the
characters being written to the present stream.
7. Write(Decimal): This method is used to write a decimal value to the
present stream and also it advances the position of the current stream
by sixteen bytes.
8. Write(Double): This method is used to write an eight-byte floating-point
value to the present stream and then it also advances the position of
the current stream by eight bytes.
9. Write(Int32): This method is used to write a four-byte signed integer to
the present stream and then it advances the position of the current
stream by four bytes.
What is BinaryReader class in C#?

 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.

Methods of BinaryReader Class in C#:

The BinaryReader class in C# provides many Read() methods to read


different primitive data types from a stream. Such as the ReadString() method
of BinaryReader is used to read the next byte as a string value and also it
advances the current position in the stream by one byte. The different types
of Read() methods of BinaryReader class are as follows:

1) Read(): It is used to read characters from the underlying stream and


advances the current position of the stream in accordance with the
Encoding used and the specific character being read from the stream.
It returns the next character from the input stream, or -1 if no characters
are currently available.
2) ReadBoolean(): It is used to read a Boolean value from the current
stream and advances the current position of the stream by one byte. It
returns true if the byte is nonzero; otherwise, false.
3) ReadByte(): It is used to read the next byte from the current stream and
advances the current position of the stream by one byte. It returns the
next byte read from the current stream.
4) ReadChar(): It is used to read 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. It returns a character read from the current
stream.
5) ReadDecimal(): It is used to read a decimal value from the current
stream and advances the current position of the stream by sixteen
bytes. It returns a decimal value read from the current stream.
6) ReadDouble(): It is used to read an 8-byte floating-point value from the
current stream and advances the current position of the stream by
eight bytes. It returns an 8-byte floating-point value read from the
current stream.
7) ReadInt32(): It is used to read a 4-byte signed integer from the current
stream and advances the current position of the stream by four bytes.
It returns a 4-byte signed integer read from the current stream.
8) ReadInt64(): It is used to read an 8-byte signed integer from the current
stream and advances the current position of the stream by four bytes.
It returns an 8-byte signed integer read from the current stream.
9) ReadString(): It is used to read a string from the current stream. The
string is prefixed with the length, encoded as an integer seven bits at a
time. It returns the string being read.

StringWriter and StringReader in C#


What is StringWriter Class in C#?

 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#

1) public StringWriter(): It initializes a new instance of the


System.IO.StringWriter class.
2) public StringWriter(IFormatProvider formatProvider): It initializes a new
instance of the StringWriter class with the specified format control. The
parameter formatProvider specifies a System.IFormatProvider object
that controls formatting
3) public StringWriter(StringBuilder sb): It initializes a new instance of the
StringWriter class that writes to the specified System.Text.StringBuilder.
The parameter sb specifies the StringBuilder object to write to.
4) public StringWriter(StringBuilder sb, IFormatProvider formatProvider): It
initializes a new instance of the StringWriter class that writes to the
specified StringBuilder and has the specified format provider. The
parameter sb specifies the StringBuilder object to write to and the
parameter formatProvider specifies a System.IFormatProvider object
that controls formatting.
Properties of StringWriter Class in C#:
The StringWriter class in C# provides the following property.

 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#?

 The StringReader class in C# is derived from the TextReader class and


this StringReader class is mainly used to manipulate strings rather than
files. This StringReader class is built using a string and Read and
ReadLine methods are provided by StringReader class to read the
parts of the string. The data read by the StringReader class is the data
written by the StringWriter class which is derived from the TextWriter
subclass. The data can be read in a synchronous manner or in an
asynchronous manner using StringReader class and the read
operations are performed by using the constructors and methods
present in the StringReader Class.
 So, in simple words, we can say that the StringReader class in C#
implements TextReader class that reads a string from a string. It enables
you to read a string synchronously or asynchronously. You can read a
character with Read() method and read a line with ReadLine()
method. If you go to the definition of StringReader class, then you will
see the following.
The Constructor of StringReader Class in C#

public StringReader(string s): It initializes a new instance of the StringReader


class that reads from the specified string. Here, the parameter “s” specifies
the string to which the StringReader should be initialized.
Methods of StringReader Class in C#
The StringReader class in C# provides the following methods.

1) Close(): This method is used to close the StringReader.


2) Peek(): This method is used to return the next available character but
does not consume it. It returns an integer representing the next
character to be read, or -1 if no more characters are available or the
stream does not support seeking.
3) Read(): This method is used to read the next character from the input
string and advances the character position by one character. It returns
the next character from the underlying string, or -1 if no more
characters are available.
4) ReadLine(): This method is used to read a line of characters from the
current string and returns the data as a string. It returns the next line
from the current string, or null if the end of the string is reached.
5) ReadLineAsync(): This method is used to read a line of characters
asynchronously from the current string and returns the data as a string.
It returns a task that represents the asynchronous read operation. The
value of the TResult parameter contains the next line from the string
reader or is null if all the characters have been read.
6) ReadToEnd(): This method is used to read all characters from the
current position to the end of the string and returns them as a single
string. It returns the content from the current position to the end of the
underlying string.
7) ReadToEndAsync(): This method is used to read all characters from the
current position to the end of the string asynchronously and returns
them as a single string. It returns a task that represents the
asynchronous read operation. The value of the TResult parameter
contains a string with the characters from the current position to the
end of the string.
8) Dispose(): This method is used to release the unmanaged resources
used by the System.IO.StringReader and optionally releases the
managed resources.
FileInfo Class in C#
What is FileInfo Class in C#?

 The FileInfo class in C# is used for manipulating files such as creating,


deleting, removing, copying, opening, and getting information. The
FileInfo class provides several properties and methods that make file
manipulation easy. FileInfo class is used for typical file operations like
copying, moving, renaming, creating, opening, deleting, and
appending files. By default, full read/write access to new files is granted
to all users.
 The FileInfo class in C# belongs to the System.IO namespace. It is a
sealed class, and hence, it cannot be inherited. If you go to the
definition of the FileInfo class, you will see the following.

The Constructor of FileInfo Class in C#


The FileInfo Class provides the following Constructor

 public FileInfo(string fileName): It initializes a new instance of the


System.IO.FileInfo class, which acts as a wrapper for a file path. The
parameter fileName specifies the fully qualified name of the new file or
the relative file name. Do not end the path with the directory separator
character.
Properties of FileInfo Class in C#
The FileInfo Class provides the following properties.

1) Directory: It is used to get an instance of the parent directory. It returns


a DirectoryInfo object representing the parent directory of this file.
2) DirectoryName: It gets a string representing the directory’s full path. It
returns a string representing the directory’s full path.
3) Length: It is used to get the size, in bytes, of the current file. It returns the
size of the current file in bytes.
4) Name: It is used to get the name of the file.
5) IsReadOnly: It is used to get or set a value determining whether the
current file is read-only. It returns true if the current file is read-only;
otherwise, false.
6) Exists: It is used to get a value indicating whether a file exists. It returns
true if the file exists, false if it does not exist, or if it is a directory.
FileInfo Class Methods in C#
The FileInfo class in C# provides the following methods.

1) public StreamWriter AppendText(): This method is used to get a value


indicating whether a file exists. It returns true if the file exists, false if it
does not exist, or if it is a directory.
2) public FileInfo CopyTo(string destFileName): This method is used to
copy an existing file to a new one, disallowing the overwriting of an
existing one. It returns a new file with a fully qualified path. The
parameter destFileName specifies the name of the new file to copy to.
3) public FileInfo CopyTo(string destFileName, bool overwrite): This
method is used to copy an existing file to a new one, allowing the
overwriting of an existing one. It returns a new file or an overwrite of an
existing file if overwrite is true. If the file exists and overwrite is false, an
IOException is thrown. The parameter destFileName specifies the name
of the new file to copy to, and the parameter overwrites specifies true
to allow an existing file to be overwritten; otherwise, false.
4) public FileStream Create(): This method creates and returns a new file.
5) public StreamWriter CreateText(): This method creates a StreamWriter
that writes a new text file.
6) public void Decrypt(): This method is used to decrypt a file encrypted
by the current account using the System.IO.FileInfo.Encrypt method.
7) public override void Delete(): This method permanently deletes a file.
8) public void Encrypt(): This method is used to encrypt a file so that only
the account used to encrypt the file can decrypt it.
9) public FileSecurity GetAccessControl(): This method is used to get a
System.Security.AccessControl.FileSecurity object that encapsulates
the access control list (ACL) entries for the file described by the current
System.IO.FileInfo object. That means this method returns a
System.Security.AccessControl.FileSecurity object that encapsulates
the access control rules for the current file.
10)public void MoveTo(string destFileName): This method moves a
specified file to a new location, providing the option to specify a new
file name. Here, the destFileName parameter specifies the path to
move the file to, which can specify a different file name.
11)public FileStream Open(FileMode mode): This method opens a file in
the specified mode. It returns a file opened in the specified mode, with
read/write access and unshared
12)public FileStream Open(FileMode mode, FileAccess access): This
method is used to open a file in the specified mode with read, write, or
read/write access. It returns a System.IO.FileStream object opened in
the specified mode, accessed, and unshared.
13)public FileStream Open(FileMode mode, FileAccess access, FileShare
share): This method opens a file in the specified mode with read, write,
or read/write access and the specified sharing option. It returns a
FileStream object opened with the specified mode, access, and
sharing options. Here, the parameter mode specifies a
System.IO.FileMode constant specifying the mode (for example, Open
or Append) in which to open the file. The parameter access specifies a
System.IO.FileAccess constant specifying whether to open the file with
Read, Write, or ReadWrite file access, and the parameter share
specifies a System.IO.FileShare constant specifying the type of access
other FileStream objects have to this file.
14)public FileStream OpenRead(): This method creates and returns a new
read-only System.IO.FileStream.
15)public StreamReader OpenText(): This method creates
System.IO.StreamReader with UTF8 encoding that reads from an
existing text file. It returns a new StreamReader with UTF8 encoding.
16)public FileStream OpenWrite(): This method creates a write-only
System.IO.FileStream. It returns a write-only unshared
System.IO.FileStream object for a new or existing file.
17)public FileInfo Replace(string destinationFileName, string
destinationBackupFileName): This method is used to replace the
contents of a specified file with the file described by the current
System.IO.FileInfo object, deleting the original file and creating a
backup of the replaced file. It returns a System.IO.FileInfo object that
encapsulates information about the file described by the destFileName
parameter.
18)public void SetAccessControl(FileSecurity fileSecurity): This method is
used to apply access control list (ACL) entries described by a
System.Security.AccessControl.FileSecurity object to the file described
by the current System.IO.FileInfo object.
19)public override string ToString(): This method returns the path as a string.
DirectoryInfo Class in C#
What is DirectoryInfo in C#?

 The DirectoryInfo Class in C# is a class that is available inside the


System.IO namespace. The DirectoryInfo class contains almost a similar
feature as the FileInfo class of C#. The only difference is that the
DirectoryInfo focuses only on the Directory, not the file systems. So,
when we talk about the DirectoryInfo class, we talk about the physical
directory. With its help, we get the object with which we can create,
delete, and also, we can make some subdirectorys, and many more
operations can be performed.
 It provides several methods to perform operations related to directories
and subdirectories. It is a sealed class, and hence it cannot be
inherited. You will see the following if you go to the definition of
DirectoryInfo class.

The Constructor of DirectoryInfo Class in C#


The DirectoryInfo class provides the following Constructor

 public DirectoryInfo(string path): It initializes a new instance of the


DirectoryInfo class on the specified path. Here, the variable path
specifies the path to create the DirectoryInfo.
Properties of DirectoryInfo Class in C#
The DirectoryInfo class provides the following properties.
1) Parent: It is used to get the parent directory of a specified subdirectory.
It returns the parent directory or null if the path is null or if the file path
denotes a root (such as “\”, “C:”, or * “\\server\share”).
2) FullName: It is used to get the full path of the directory. It returns a string
containing the full path.
3) Name: It is used to get the name of this System.IO.DirectoryInfo
instance. It returns the directory name.
4) Exists: It is used to get a value indicating whether the directory exists. It
returns true if the directory exists; otherwise, false.
5) Root: It is used to get the root portion of the directory. It returns an
object that represents the root of the directory.
6) CreationTime: It is used to get or set the creation time of the current file
or directory. It returns the creation date and time of the current
System.IO.FileSystemInfo object.
7) LastAccessTime: It is used to get or set the time the current file or
directory was last accessed. It returns the time that the current file or
directory was last accessed.
8) LastWriteTime: It is used to get or set the time when the current file or
directory was last written. It returns the time the current file was last
written.
9) Extension: It is used to get the string representing the extension part of
the file. It returns a string containing the System.IO.FileSystemInfo
extension.
DirectoryInfo Class Methods in C#
The DirectoryInfo class in C# provides the following methods.

1) Create(): This method is used to create a directory.


2) Create(DirectorySecurity directorySecurity): This method creates a
directory using a DirectorySecurity object. The directorySecurity
parameter specifies the access control to apply to the directory.
3) CreateSubdirectory(string path): This method creates a subdirectory or
subdirectory on the specified path. The specified path can be relative
to this instance of the DirectoryInfo class. The parameter path specified
path.
4) CreateSubdirectory(string path, DirectorySecurity directorySecurity):
This method creates a subdirectory or subdirectories on the specified
path with the specified security. The specified path can be relative to
this instance of the DirectoryInfo class. The parameter path specified
path. This cannot be a different disk volume or Universal Naming
Convention (UNC) name. The directorySecurity parameter specifies the
security to apply.
5) Delete(): This method is used to delete the DirectoryInfo if it is empty.
6) Delete(bool recursive): This method is used to delete this instance of a
DirectoryInfo, specifying whether to delete subdirectories and files. The
recursive parameter specifies true to delete this directory, its
subdirectories, and all files; otherwise, it is false.
7) EnumerateDirectories(): This method returns an enumerable collection
of directory information in the current directory. It returns an
enumerable collection of directories in the current directory.
8) EnumerateFiles(): This method returns an enumerable file information
collection in the current directory. It returns an enumerable collection
of the files in the current directory.
9) GetAccessControl(): This method is used to get the DirectorySecurity
object that encapsulates the access control list (ACL) entries for the
directory described by the current DirectoryInfo object. This method
returns a DirectorySecurity object that encapsulates the access control
rules for the directory.
10)GetDirectories(): This method returns the subdirectories of the current
directory. It returns an array of System.IO.DirectoryInfo objects.
11)GetFiles(): This method returns a file list from the current directory. It
returns an array of type System.IO.FileInfo.
12)MoveTo(string destDirName): This method moves a DirectoryInfo
instance and its contents to a new path. The parameter destDirName
specifies the name and path to which to move this directory. The
destination cannot be another disk volume or a directory with an
identical name. It can be an existing directory to which you want to
add this directory as a subdirectory.
13)SetAccessControl(DirectorySecurity directorySecurity): This method is
used to set access control list (ACL) entries described by a
DirectorySecurity object. The parameter directorySecurity specifies an
object that describes an ACL entry to apply to the directory described
by the path parameter.
14)ToString(): It returns the original path that the user passed.

You might also like