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

C#Files

The document discusses file handling in C# and the System.IO namespace. It describes files and streams, and how files become streams when opened. It covers the FileStream class, which provides stream access for file operations. FileStream requires a path, FileMode to open or create, FileAccess for read/write permissions, and FileShare for concurrent access.

Uploaded by

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

C#Files

The document discusses file handling in C# and the System.IO namespace. It describes files and streams, and how files become streams when opened. It covers the FileStream class, which provides stream access for file operations. FileStream requires a path, FileMode to open or create, FileAccess for read/write permissions, and FileShare for concurrent access.

Uploaded by

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

C# System.

IO
File Handling in C# with Examples
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 traveling 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). There are two types of streams are used:

1. Input stream: This stream is used to read data from a file, which is known as a read
operation.
2. Output stream: This stream is used to write data into a file, which is known as a write
operation.

Why do I need to Learn File Handling in C#?

As a C# programmer, several times you need to save information on a disk. You will not get a
database everywhere to save the information and your project may require saving information
in a text file, doc file, xls file, pdf file, or any other file types. So, you must know the concept of
saving data in a file.

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, two basic operations we mostly perform on a file that is reading data from a file and
writing data to a 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.

Then the next question that should come to your mind is what is a stream? 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. A stream is a sequence of bytes
traveling from a source to a destination over a communication path.

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.

System.IO Namespace in C#
In C#, The System.IO namespace contains the required classes which are used to handle the
input and output streams and also provide information about file and directory structure. The
parent class of file processing is Stream. Stream is an abstract class, which is used as the parent
of the classes that actually implement the necessary operations.
Please have a look at the below image which shows the file handling class hierarchy in C#.

Note: The FileInfo, DirectoryInfo, and DriveInfo classes have instance methods. File, Directory,
and Path classes have static methods. The following table describes commonly used classes in
the System.IO namespace.
FileStream Class in C# with Examples
What is FileStream Class in C#?
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 in C#, first of all, we need to include the System.IO namespace
and then we need to create an instance of the FileStream object to create a new file or open
an existing file. If you go to the definition of FileStream class, you will see that there are many
overloaded versions of Constructors available as shown in the below image.

The simplest way to create an instance of FileStream class is to use the following overloaded
version of the Constructors.

public FileStream(string path, FileMode mode): This Constructor Initializes a new instance of
the FileStream class with the specified path and creation mode.

Here,

1. path: A relative or absolute path for the file that the current FileStream object will
encapsulate.
2. mode: A constant that determines how to open or create the file.

public FileStream(string path, FileMode mode, FileAccess access): This overloaded version
initializes a new instance of the FileStream class with the specified path, creation mode, and
read/write permission.

Here,

1. path: A relative or absolute path for the file that the current FileStream object will
encapsulate.
2. mode: A constant that determines how to open or create the file.
3. access: A constant that determines how the file can be accessed by the FileStream
object. This also determines the values returned by the System.IO.FileStream.CanRead
and System.IO.FileStream.CanWrite properties of the FileStream object.
System.IO.FileStream.CanSeek is true if the path specifies a disk file.
public FileStream(string path, FileMode mode, FileAccess access, FileShare share): This
overloaded version is Initializes a new instance of the System.IO.FileStream class with the
specified path, creation mode, read/write permission, and sharing permission.

Here

1. path: A relative or absolute path for the file that the current FileStream object will
encapsulate.
2. mode: A constant that determines how to open or create the file.
3. access: A constant that determines how the file can be accessed by the FileStream
object. This also determines the values returned by the System.IO.FileStream.CanRead
and System.IO.FileStream.CanWrite properties of the FileStream object.
System.IO.FileStream.CanSeek is true if the path specifies a disk file.
4. share: A constant that determines how the file will be shared by processes.

FileMode in C#:
The FileMode specifies how the operating system should open a file. If you go to the definition
of FileMode, then you will see that it is an enum with the following structure.

It has the following six constant values.

1. CreateNew: It specifies that the operating system should create a new file. This
requires System.Security.Permissions.FileIOPermissionAccess.Write permission. If the
file already exists, a System.IO.IOException exception is thrown.
2. Create: It specifies that the operating system should create a new file. If the file
already exists, it will be overwritten. This requires
System.Security.Permissions.FileIOPermissionAccess.Write permission.
FileMode.Create is equivalent to requesting that if the file does not exist, use
System.IO.FileMode.CreateNew; otherwise, use System.IO.FileMode.Truncate. If the
file already exists but is a hidden file, an System.UnauthorizedAccessException
exception is thrown.
3. Open: It specifies that the operating system should open an existing file. The ability to
open the file is dependent on the value specified by the System.IO.FileAccess
enumeration. A System.IO.FileNotFoundException exception is thrown if the file does
not exist.
4. OpenOrCreate: It specifies that the operating system should open a file if it exists;
otherwise, a new file should be created. If the file is opened with FileAccess.Read,
System.Security.Permissions.FileIOPermissionAccess.Read permission is required. If
the file access is FileAccess.Write,
System.Security.Permissions.FileIOPermissionAccess.Write permission is required. If
the file is opened with FileAccess.ReadWrite, both
System.Security.Permissions.FileIOPermissionAccess.Read and
System.Security.Permissions.FileIOPermissionAccess.Write permissions are required.
5. Truncate: It specifies that the operating system should open an existing file. When the
file is opened, it should be truncated so that its size is zero bytes. This requires
System.Security.Permissions.FileIOPermissionAccess.Write permission. Attempts to
read from a file opened with FileMode.Truncate causes a System.ArgumentException
exception.
6. Append: It opens the file if it exists and seeks the end of the file, or creates a new file.
This requires System.Security.Permissions.FileIOPermissionAccess.Append permission.
FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek
a position before the end of the file throws a System.IO.IOException exception, and
any attempt to read fails and throws a System.NotSupportedException exception.

FileAccess in C#:
It gives permission to file for read, write, or read/write access. If you go to the definition of
FileAccess, then you will see that it is an enum with the following structure.

It has the following three constant values.

1. Read– It gives read access to the file. Data can be read from the file. Combine with
Write for read/write access.
2. Write – It gives Write access to the file. Data can be written to the file. Combine with
Read for read/write access.
3. ReadWrite – It gives read and writes access to the file. Data can be written to and read
from the file.
FileShare in C#:
It contains constants for controlling the kind of access other FileStream objects can have to the
same file. That means it opens a file with share permission. If you go to the definition of
FileShare, you will see that it is an enum with the following structure.

It has the following six constant values.

1. None: Declines sharing of the current file. Any request to open the file (by this process
or another process) will fail until the file is closed.
2. Read: Allows subsequent opening of the file for reading. If this flag is not specified, any
request to open the file for reading (by this process or another process) will fail until
the file is closed. However, even if this flag is specified, additional permissions might
still be needed to access the file.
3. Write: Allows subsequent opening of the file for writing. If this flag is not specified, any
request to open the file for writing (by this process or another process) will fail until
the file is closed. However, even if this flag is specified, additional permissions might
still be needed to access the file.
4. ReadWrite: Allows subsequent opening of the file for reading or writing. If this flag is
not specified, any request to open the file for reading or writing (by this process or
another process) will fail until the file is closed. However, even if this flag is specified,
additional permissions might still be needed to access the file.
5. Delete: Allows subsequent deleting of a file.
6. Inheritable: Makes the file handle inheritable by child processes. This is not directly
supported by Win32.

Example to Understand FileStream class in C#:


In the below example, we will create a new file called “MyFile.txt” and saves it on the disk. And
then we will open this file, saves some text in it, and then close this file.
File Creation Example using FileSteam Class in C#:
In the below example, first, we created an instance of FileStream class to create a new
MyFile.txt file in the D drive.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
//Set the File Path
string FilePath = @"D:\MyFile.txt";
FileStream fileStream = new FileStream(FilePath, FileMode.Create);
fileStream.Close();
Console.Write("File has been created and the Path is D:\\MyFile.txt");
Console.ReadKey();
}
}
}
When you run the above code, you will get the following output.

File Creation Example using FileSteam Class in C#

File Open and Write Example using FileSteam Class in C#:


The MyFile.txt file is created on the D drive. Now we will open this file and we will write some
text in it. In the below example, first, we created an instance of FileStrem class. Then Encoded
a string into bytes and kept it into byte[] variable bdata and finally using Write() method of
FileStream stored the string into the file.

using System;
using System.IO;
using System.Text;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
//Set the File Path
string FilePath = @"D:\MyFile.txt";
FileStream fileStream = new FileStream(FilePath, FileMode.Append);
byte[] bdata = Encoding.Default.GetBytes("C# Is an Object Oriented Programming
Language");
fileStream.Write(bdata, 0, bdata.Length);
fileStream.Close();
Console.WriteLine("Successfully saved file with data : C# Is an Object Oriented
Programming Language");
Console.ReadKey();
}
}
}
When you run the above code, you will get the following output.

File Open and Write Example using FileSteam Class in C#

File Read Example using FileStream Class in C#:


We have already created one MyFile.txt and also, we also we have written some data into it.
Now, we will see, how to read the data from the MyFile.txt file. In the below example, we have
opened the file with the Read permission and used StreamReader class to read the file and
then print the data in the console.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string FilePath = @"D:\MyFile.txt";
string data;
FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
using (StreamReader streamReader = new StreamReader(fileStream))
{
data = streamReader.ReadToEnd();
}
Console.WriteLine(data);
Console.ReadLine();
}
}
}
When you run the above code, you will get the following output.

File Read Example using FileStream Class in C#

Note: The FileStream class in C# is used for reading and writing files. It is part of the System.IO
namespace. To manipulate files using FileStream, you need to create an object of FileStream
class. This object has four parameters; the Name of the File, FileMode, FileAccess, and
FileShare.
StreamReader and StreamWriter in C# with Examples
In this article, I am going to discuss StreamReader and StreamWriter in C# with Examples.
Please read our previous article where we discussed FileStream Class in C# with Examples. At
the end of this article, you will understand what StreamReader and StreamWriter are in C# and
when and how to use StreamReader and StreamWriter in C# with Examples.

StreamWriter Class in C#

The StreamWriter class in C# is more popular in File Handling and it is very helpful in writing
text data in the file. It is easy to use and provides a complete set of constructors and methods
to work.

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. StreamWriter class in C# is used for writing characters to stream in a
particular format.

As you can see in the above image, this class contains lots of methods, different types of
constructors, and a few properties.
Constructor:

StreamWriter(): The Constructor is used to initialize a new instance of the


System.IO.StreamWriter class for the specified. 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.

Example to write user input to a file using StreamWriter Class in C#:

It is very easy to write data into a text file using StreamWriter Class and most beginners prefer
to use this class in writing files.

In the below example, we are using the StreamWriter constructor version (public
StreamWriter(string path);) which takes the string path as an argument to create an instance
of StreamWriter class. This StreamWriter instance will create a file with the name MyFile.txt at
the specified location i.e. in the D Drive. Using the Console.ReadLine() method we are taking
the input data from the user which we will store in our MyFile.txt file. When we call the Write
method passing the string data, it will write the string data into the stream i.e. into the text
file. Finally, we call the Flush and Close method to clear all the buffers as well as close the
stream.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
// This will create a file named MyFile.txt at the specified location i.e. in the D Drive
// Here we are using the StreamWriter constructor which takes the string path as an
argument to create an instance of StreamWriter class
StreamWriter sw = new StreamWriter("D://MyFile.txt");
//Asking user to enter the text that we want to write into the MyFile.txt file
Console.WriteLine("Enter the Text that you want to write on File");
// To read the input from the user
string str = Console.ReadLine();
// To write the data into the stream
sw.Write(str);
// Clears all the buffers
sw.Flush();
// To close the stream
sw.Close();
Console.ReadKey();
}
}
}
Output:

Example to write user input to a file using StreamWriter Class in C#

Now, you will see that, it will create a text file with the name MyFile.txt in the D drive and once
you open the file you will see the following data written inside it.

Save Variable Data to File in C# using StreamWriter Class

Several times you need to save variable data in a file. These variable data might be the output
of our program, log details, exceptions, errors, etc. Now, let us see, how can we can save
variable data in a file using StreamWriter Class.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string file = @"D:\MyTextFile1.txt";
int a, b, result;
a = 15;
b = 20;
result = a + b;
using (StreamWriter writer = new StreamWriter(file))
{
writer.Write("Sum of {0} + {1} = {2}", a, b, result);
}
Console.WriteLine("Saved");
Console.ReadKey();
}
}
}

Now open the D:\MyTextFile1.txt file and you will see the following text.

Sum of 15 + 20 = 25

StreamReader Class in C#

The StreamReader class in C# allows us to read text files easily. Its implementation is easy and
it is widely popular among the 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 defaults.
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.

As you can see in the above image, the StreamReader class contains lots of methods, different
types of constructors, and a few properties.
Constructor:

StreamReader()

It initializes a new instance of the StreamReader class for the specified stream. It has different
overloaded versions.

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

Properties:

1. CurrentEncoding: It gets the current character encoding that the current


System.IO.StreamReader object is using.
2. EndOfStream: It gets a value that indicates whether the current stream position is at
the end of the stream.
3. BaseStream: It returns the underlying stream.
4.

Example to read from a file using StreamReader Class in C#:

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
//Creating a new input stream i.e. MyFile.txt and opens it
StreamReader sr = new StreamReader("D://MyFile.txt");
Console.WriteLine("Content of the File");
// This is used to specify from where to start reading input stream
sr.BaseStream.Seek(0, SeekOrigin.Begin);
// To read line from input stream
string str = sr.ReadLine();
// To read the whole file line by line
while (str != null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
Console.ReadLine();
// to close the stream
sr.Close();
Console.ReadKey();
}
}
}
Output:

Example to read from a file using StreamReader Class in C#

StreamReader and StreamWriter class Example in C#

As discussed, it is very easy to read a text file using StreamReader Class. In the below example,
we are doing the following thing:

. Write some data on a text file using StreamWriter class

. Read those data using StreamReader class.

Example:

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string file = @"D:\MyTextFile2.txt";
using (StreamWriter streamWriter = new StreamWriter(file))
{
streamWriter.WriteLine("Hellow StreamWriter Class in C#");
streamWriter.WriteLine("How are you Doing?");
}
//Reading text file using StreamReader Class
using (StreamReader reader = new StreamReader(file))
{
Console.WriteLine(reader.ReadToEnd());
}
Console.ReadKey();
}
}
}
Output:

StreamReader and StreamWriter class Example in C#


File Class in C# with Examples

File Class in C#

The File Class in C# provides some static methods to perform most of the 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. By
default, all existing contents are removed from the file, 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 and if you go to the definition of
the File class, you will find 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 Copies an existing file to a new file. Overwriting a file of
the same name is not allowed.
2. Create: This method is used to create or overwrite it in the specified path.
3. Decrypt: This method is used to Decrypt a file that was 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 is used to open 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 contents of the file
into a byte array, and then close the file.
13. ReadAllLines: This method is used to Open a file, reads 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, reads 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 the contents of a specified file with the
contents of another file, 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.

Example to Understand File Class in C#:

The C# Language and .Net Framework can work with files with the help of several methods of
File class. Let us see how to use the File class methods to perform different file operations with
some examples. Let us assume that we have a file in the D drive called MyFile.txt. The
MyFile.txt file will be a simple text file and have 2 lines of data as follows:

Learn C#.NET By Dot Net Tutorials

C# is one of the Object-Oriented Programming Language

Now, we will create a simple Console application and will work with File methods. In the
console application, all code is going to write inside the program.cs class file.
Exists Method of File Class in C#

The Exists method of File Class in C# is used to check if a particular file is existing or not. This
method will return true if the caller has the required permissions and the path contains the
name of an existing file; otherwise, false. This method also returns false if the path is null, an
invalid path, or a zero-length string. If the caller does not have sufficient permissions to read
the specified file, no exception is thrown and the method returns false regardless of the
existence of the path.

Now, let’s see the code which can be used to check if our MyFile.txt file exists or not. So, copy
and paste the below code. The Exits is a static method of File class, so we are calling this
method with the class name i.e. File. This method expects one parameter which is the file
path.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\MyFile.txt";
if (File.Exists(path))
{
Console.WriteLine("MyFile.txt File Exists in D Directory");
}
else
{
Console.WriteLine("MyFile.txt File Does Not Exist in D Directory");
}
Console.ReadKey();
}
}
}
Code Explanation:

Here, first, we are storing the MyFile.txt file path in a string variable called path. Then, we use
the Exists method to check if the file exists or not. If the File exists in the specified path, a true
value will be returned.

If we get a true value then we write the message “MyFile.txt File Exists in D Directory” to the
console window else If we get false then we write the message “MyFile.txt File Does Not Exist
in D Directory” to the console window. So, when you run the above code, you will get the
following output.
ReadAlllines Method of File Class in C#:

The ReadAlllines Method of File Class is used to open a file and read all the lines one by one in
the file and then close the file. The lines are then stored in a string array variable. Let us see an
example for a better understanding.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\MyFile.txt";
if (File.Exists(path))
{
string[] lines= File.ReadAllLines(path);
foreach(var line in lines)
{
Console.WriteLine(line);
}
}
else
{
Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
}
Console.ReadKey();
}
}
}
Code Explanation:

In the above example, first, we are creating a string variable to store the file path. Then we are
checking whether the file exists or not using the Exists method. If the file exists, then we are
reading all the lines from the file by using the File.ReadAllLines method and store it in a string
array. Then we are using a foreach loop to read all the lines one by one and print the same on
the console window. As our file contains two lines of data, so when you run the above code,
you will get the following output.
ReadAllText Method of File Class in C#

The ReadAllText Method of File Class in C# is used to read all the lines in a file at once. The
lines are then stored in a string variable. Let us see an example for a better understanding.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\MyFile.txt";
if (File.Exists(path))
{
string lines= File.ReadAllText(path);
Console.WriteLine(lines);
}
else
{
Console.WriteLine("MyFile.txt File Does not Exists in D Directory");
}
Console.ReadKey();
}
}
}
Code Explanation:

In the above example, first, we are creating a string variable called the path to store the file
path. Then we are checking whether the file exists or not using the Exists method of File Class.
If the file exists, then we are reading all the lines from the file at once by using the ReadAllText
method of the File class and storing the result in a string variable. Then we print the same on
the console window. When you run the above code, you will get the following output.

Copy Method of File Class in C#:

The Copy Method of File Class in C# is used to make a copy of an existing file. The most
important point that you need to remember is Overwriting a file of the same name is not
allowed using File.Copy method. The Copy method takes two parameters. The first parameter
is the sourceFileName i.e. the file to copy and the second parameter is the destFileName i.e.
the name of the destination file and the destination file cannot be a directory or an existing
file. Let us see an example for a better understanding.
using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string SourceFilePath = @"D:\MyFile.txt";
string DestinationFilePath = @"D:\MyFile2.txt";
if (File.Exists(SourceFilePath))
{
File.Copy(SourceFilePath, DestinationFilePath);
string lines= File.ReadAllText(DestinationFilePath);
Console.WriteLine(lines);
}
else
{
Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
}
Console.ReadKey();
}
}
}
Code Explanation:

In the above example, first, we are creating two string variables called SourceFilePath and
DestinationFilePath to store the source and destination file paths respectively. Then we are
checking whether the source file exists or not using the File.Exists method. If the source file
exists, we are calling File.Copy method to copy the source file MyFile.txt file to the destination
file MyFile2.txt. Then we print the destination file data on the console window. So, when you
run the above code, you will get the following output.

Now you can see that MyFile2.txt should be created inside the D drive. The point that you
need to remember is the destination file cannot be a directory or an existing file. For example,
the MyFile2.txt file is already created inside the D drive, now again if you run the same code,
you will get the following exception.
There is another overloaded version of the Copy method available inside the File class with the
following signature. You can pass the third parameter as true or false to override an existing
file. So, the overloaded version of the Copy method is used to copy an existing file to a new
file. Overwriting a file of the same name is allowed.

public static void Copy(string sourceFileName, string destFileName, bool overwrite);

So, let us modify the previous example and lets us use the overloaded version, and see the
output.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string SourceFilePath = @"D:\MyFile.txt";
string DestinationFilePath = @"D:\MyFile2.txt";
if (File.Exists(SourceFilePath))
{
File.Copy(SourceFilePath, DestinationFilePath, true);
string lines= File.ReadAllText(DestinationFilePath);
Console.WriteLine(lines);
}
else
{
Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
}
Console.ReadKey();
}
}
}
Now, run the above application and you will not get any errors.
Delete Method of File Class in C#:

The Delete method of File Class in C# is used to delete an existing file. The Delete method of
the File class takes one parameter which is the path of the file to be deleted. Let us see an
example for a better understanding.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string FilePath = @"D:\MyFile2.txt";
if (File.Exists(FilePath))
{
File.Delete(FilePath);
Console.WriteLine("MyFile2.txt File Deleted");
}
else
{
Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
}
Console.ReadKey();
}
}
}
Code Explanation:

In the above example, first, we are creating a string variable called FilePath to store the file
path. Then we are checking whether the file exists using the File.Exists method. If the file
exists, we are calling File.Delete method passing the file path to delete file MyFile2.txt file. So,
when you run the above code, you will get the following output.

Create Method of File Class in C#

The Create Method of File Class in C# is used to create a file in the specified folder. There are
multiple overloaded versions of this method is available in the File class. They are as follows:

public static FileStream Create(string path): Creates or overwrites a file in the specified path.

1. 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.
2. 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.
3. 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: Please note that all the above-overloaded versions return an instance of FileStream
class. So, we need to close the stream object by calling the Close method.

Let us understand Create method with an example. In the below example apart from the
Create method, I am also using the WriteAllLines method which will write the data into the
specified file.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
//Set the File Path
string FilePath = @"D:\MyFile3.txt";
//Create the File
FileStream fs = File.Create(FilePath);
fs.Close();
if (File.Exists(FilePath))
{
//Writing Content to File
string[] content = { "Hello", "And", "Welcome" };
File.WriteAllLines(FilePath, content);
Console.WriteLine("MyFile3.txt File Created with the Following Data");
string fileContent = File.ReadAllText(FilePath);
Console.WriteLine(fileContent);
}
else
{
Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
}
Console.ReadKey();
}
}
}
Code Explanation:

In the above example, first, we create a string variable called FilePath which we are going to
create using the Create method. Then we are calling the Create method passing the FilePath
which will create the MyFile3.txt file in the D drive and then immediately we close the
FileStream object by calling the Close method. Then we are checking whether the MyFile3.txt
file exists or not using the File.Exists method. If the MyFile3.txt file exists, then we are creating
a string array and then calling the WriteAllLines method passing the FilePath and string array.
This WriteAllLines method will write the string array data into the specified file. And finally, we
are reading the content of the MyFile3.txt file and printing it on the Console. So, when you run
the above code, you will get the following output.
TextWriter and TextReader in C# with Examples

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.

How TextWriter work in C#?

To work with TextWriter in C#, first, we need to import the System.IO namespace. We cannot
directly create an instance of TextWriter using the new keyword as it is an abstract class. So, to
create the instance we need to use the CreateText() method of the File class as follows:

TextWriter textWriter = File.CreateText(filePath);

The File.CreateText method takes the path of the file to be opened for writing. It creates or
opens a file for writing UTF-8 encoded text. If the file already exists, then its content will be
overwritten. The File.CreateText(filePath) method returns an instance of StreamWriter class,
which is one of the derived classes of the TextWriter abstract class. Now, with the help of this
instance, we can call the methods of TextWriter class to write text into a file.

Like StreamWriter there are also other classes that are derived from the TextWriter class and
provide the implementation for the members of TextWriter. The following is the list of derived
classes with the help of which we can work with TextWriter:

1. IndentedTextWriter: It is used to insert a tab string and to track the current


indentation level.
2. StreamWriter: It is used to write characters to a stream in a particular encoding.
3. StringWriter: It is used to write information to a string. The information is stored in an
underlying StringBuilder.
4. HttpWriter: It provides an object of TextWriter class that can be accessed through the
intrinsic HttpResponse object.
5. HtmlTextWriter: It is used to write markup characters and text to an ASP.NET server
control output stream.

Example to Understand TextWriter Class in C#:

In the below example, first, we create one string variable which holds the file path. Then we
create an instance of TextWriter class and to create an instance we call the File.CreateText
method and provide the file path where we want to create the file. Then using the WriteLine
method we write some data into the file.
using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string filePath = @"D:\MyFile1.txt";
using (TextWriter textWriter = File.CreateText(filePath))
{
textWriter.WriteLine("Hello TextWriter Abstract Class!");
textWriter.WriteLine("File Handling Tutorial in C#");
}
Console.WriteLine("Write Successful");
Console.ReadKey();
}
}
}
When you run the above code, you will get the following output.

Write Successful

Now, you can verify that the MyFile1.txt file should be created inside the D drive and with the
following data.

We can also asynchronously write characters to stream by using WriteAsync(Char) method


which is shown in the below example.

using System;
using System.IO;
namespace FileHandlingDemo
{
public class Program
{
public static void Main(string[] args)
{
WriteCharAsync();
Console.ReadKey();
}
public static async void WriteCharAsync()
{
string filePath = @"D:\MyFile2.txt";
using (TextWriter textWriter = File.CreateText(filePath))
{
await textWriter.WriteLineAsync("Hello TextWriter Abstract Class!");
await textWriter.WriteLineAsync("File Handling Tutorial in C#");
}
Console.WriteLine("Async Write Successful");
}
}
}
Note: The TextWriter class in C# is used to write text or sequential series of characters to a file.
A class derived from the TextWriter class needs to provide implementation to the members of
the TextWriter class.

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. If you go to the definition of TextReader Class, you will see that it is an abstract
class as shown in the below image.
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.

How Does TextReader Work in C#?

We cannot create an instance of TextReader class in C# because it is an abstract class.


TextReader is not threaded safe by default. The class deriving the TextReader class needs to
minimally implement Peek() and Read() methods in order to make a useful instance of
TextReader.

As TextReader is an abstract class, we cannot create its instance directly using the new
keyword but we can call the OpenText() method of the File class to achieve the same. The
OpenText() method takes the location of the file as input and then it opens an existing UTF-8
encoded text file at the same location for reading. The Syntax of creating TextReader is shown
below:

TextReader textReader = File.OpenText(filePath);

The File.OpenText() method returns an object of the StreamReader class which is the derived
class of TextReader and thus helps in creating a useful instance of TextReader class. This
instance can be used to call the methods of TextReader class to read content from the file. We
can also create a TextReader instance with the help of using block as follows:

using(TextReader textReader = File.OpenText(filePath))


{
//Code
}
The advantage of working with using block is that it releases the memory acquired by the
textReader as soon as we move from the using block. We can work with TextReader with the
help of its two derived classes i.e. StreamReader and StringReader.
1. StreamReader: It is used to read characters from a byte stream in a particular
encoding.
2. StringReader: It is used to read text from a string.

Example to Understand TextReader Class in C#:

In the below example, we will open the D:\MyFile1.txt file (which we just created in our
previous example) using the TextReader class, and then read the file and print the data on the
console.

using System;
using System.IO;
namespace FileHandlinDemo
{
class Program
{
static void Main(string[] args)
{
string filePath = @"D:\MyFile1.txt";
//Read One Line
using (TextReader textReader = File.OpenText(filePath))
{
Console.WriteLine(textReader.ReadLine());
}
//Read 4 Characters
using (TextReader textReader = File.OpenText(filePath))
{
char[] ch = new char[4];
textReader.ReadBlock(ch, 0, 4);
Console.WriteLine(ch);
}
//Read full file
using (TextReader textReader = File.OpenText(filePath))
{
Console.WriteLine(textReader.ReadToEnd());
}
Console.ReadKey();
}
}
}

Output:
BinaryWriter and BinaryReader in C# with Examples

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.

If you go to the definition of BinaryWriter class, then you will see the following structure.
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.

How to Create an Instance of BinaryWriter Class in C#?

There are four overloaded constructors available in BinaryWriter class to create a BinaryWriter
instance. They are as follows:

1. public BinaryWriter(Stream output): It initializes a new instance of the BinaryWriter


class based on the specified stream and uses UTF-8 encoding. Here, the parameter
output specifies the output stream.
2. public BinaryWriter(Stream output, Encoding encoding): It initializes a new instance of
the BinaryWriter class based on the specified stream and character encoding. Here,
the parameter output specifies the output stream and the parameter encoding
specifies the character encoding to use.
3. public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen): It initializes a
new instance of the BinaryWriter class based on the specified stream and character
encoding, and optionally leaves the stream open. Here, the parameter output specifies
the output stream and the parameter encoding specifies the character encoding to use
and the parameter leaveOpen specifies true to leave the stream open after the
BinaryWriter object is disposed otherwise, false.
4. protected BinaryWriter(): It initializes a new instance of the System.IO.BinaryWriter
class that writes to a stream.

We can create an object of BinaryWriter class inside the using block so that the memory
occupied by the object will be released automatically when the work of the object is
completed and it is no longer needed. The syntax is given below.
using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(fileName, FileMode.Create )))
{
//user code
}
Here is, File.Open() method returns the FileStream object which helps to create an instance of
BinaryWriter.

How BinaryWriter Works in C#?

In C#, the BinaryWriter class is used to write binary data to a file or we can say that it is used to
create binary files. It helps us write primitive data types such as int, char, double, etc. in binary
format to a stream. It also helps us write strings in a particular character encoding format.

In order to work with BinaryWriter in C#, first, we need to import the System.IO namespace.
Then, we need to create an instance of the BinaryWriter class by using the new operator and
bypassing a Stream object to the constructor of BinaryWriter. There are multiple versions of
Constructors available in BinaryWriter class. You can use any one of them.

To create an instance of BinaryWriter in C#, we generally provide a Stream object to its


constructor at the same time we can also provide optional parameters that specify the
encoding to be used while writing the file. In case, the user does not provide any character
encoding then UTF-8 encoding will be used by default.

The BinaryWriter class in C# provides different Write() methods for different types of data.
These methods are used to write data to the binary file.

Example to Understand BinaryWriter Class in C#

In the below example, we create a new binary file at location “D:\MyBinaryFile.bin” and then
store error log information in it.

using System;
using System.IO;
namespace FileHandlingDemo
{
class Program
{
static void Main(string[] args)
{
using (BinaryWriter writer = new BinaryWriter(File.Open("D:\\MyBinaryFile.bin",
FileMode.Create)))
{
//Writting Error Log
writer.Write("0x80234400");
writer.Write("Windows Explorer Has Stopped Working");
writer.Write(true);
}
Console.WriteLine("Binary File Created!");
Console.ReadKey();
}
}
}
When you run the above code, you will get the following output.

Now, in the D drive, the MyBinaryFile.bin file should be created and if you open this file with
visual studio, then you will see the following.

So, when you open the file D:\ MyBinaryFile.bin in the visual studio the file may look like the
above. It is hard to understand but it is a more efficient and machine-level representation of
data. This is because the data is not encoded in the text file. Don’t worry when you read your
data using BinaryReader Class you will get the exact data that you saved.

Note: The main advantages of Binary information are that it is not easily human-readable and
storing files as Binary format is the best practice for space utilization.

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.

If you go to the definition of BinaryWriter class, then you will see the following structure.
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.

How to Create an Instance of BinaryReader Class in C#?

There are three overloaded versions of constructors available in BinaryReader class to create
an instance of BinaryReader class. They are as follows:

1. public BinaryReader(Stream input): It initializes a new instance of the


System.IO.BinaryReader class based on the specified stream and using UTF-8 encoding.
Here, the parameter input specifies the input stream.
2. public BinaryReader(Stream input, Encoding encoding): It initializes a new instance of
the System.IO.BinaryReader class based on the specified stream and character
encoding. Here, the parameter input specifies the input stream and the parameter
encoding specifies the character encoding to use.
3. public BinaryReader(Stream input, Encoding encoding, bool leaveOpen): It initializes a
new instance of the System.IO.BinaryReader class based on the specified stream and
character encoding, and optionally leaves the stream open. Here, the parameter input
specifies the input stream and the parameter encoding specifies the character
encoding to use and the parameter leaveOpen specifies true to leave the stream open
after the BinaryReader object is disposed otherwise, false.
4.

How BinaryReader work in C#?

The BinaryReader class in C# is used to read binary information i.e. it is used to read data
stored in binary files (file with .bin extension). The binary file stores data in a way that can be
easily understood by a machine but for human beings, it is very difficult to understand. In
order to work with BinaryReader, first. we need to import the System.IO namespace. Then, we
need to create an instance of BinaryReader class with the help of the new operator and using
any of the available constructors. While creating the instance of BinaryReader class, we need
to pass the input stream as a parameter to the constructor.
While creating an instance of BinaryReader we can also optionally specify the character
encoding to be used if we do not specify the encoding, by default it will use UTF-8 encoding.
Along with this, we can also optionally specify if we want the stream to be opened after the
object of BinaryReader is disposed of as shown in the below statement.

BinaryReader binary_reader = new BinaryReader(inputStream, encoding, true);

Once we created the object of BinaryReader class, then with the help of different Read()
methods of BinaryReader class, we can read data from the file.

Example to Understand BinaryReader Class in C#:

In the below example I have created 2 methods WriteDataToBinaryFile() and


ReadDataFromBinaryFile(). WriteDataToBinaryFile() method is used to store some information
in D:\MyBinaryFile2.bin file and ReadDataFromBinaryFile() method is used to read data from
MyBinaryFile2.bin file and displays the data on the console.

using System;
using System.IO;
namespace FileHandlingDemo
{
class Program
{
static void Main(string[] args)
{
WriteDataToBinaryFile();
ReadDataFromBinaryFile();
Console.ReadKey();
}
static void WriteDataToBinaryFile()
{
using (BinaryWriter writer = new BinaryWriter(File.Open("D:\\MyBinaryFile2.bin",
FileMode.Create)))
{
//Writting Error Log
writer.Write("0x80234400");
writer.Write("Windows Explorer Has Stopped Working");
writer.Write(true);
}
}
static void ReadDataFromBinaryFile()
{
using (BinaryReader reader = new BinaryReader(File.Open("D:\\MyBinaryFile2.bin",
FileMode.Open)))
{
Console.WriteLine("Error Code : " + reader.ReadString());
Console.WriteLine("Message : " + reader.ReadString());
Console.WriteLine("Restart Explorer : " + reader.ReadBoolean());
}
}
}
}
Output:

Note: The BinaryWriter and BinaryReader Classes in C# are used to read and write primitive
data types and strings. If you deal only with primitive types, then this is the best stream to use.
Remember that this data is not easily readable by a human being as the contents stored in the
file are in binary form.
StringWriter and StringReader in C# with Examples

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.

Let us understand the constructors, properties, and methods of StringWriter class in C#.

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.

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

Example to Understand StringWriter Class in C#:

In the below example, we use StringWriter and StringReader Class in C#. Here, the string
variable text stores a string value, and using StringWriter, we store this string value in
StringBuilder. Then, using StringReader we get the data and displayed the data on the console.

using System;
using System.Text;
using System.IO;
namespace StringWriter_StringReader_Demo
{
class Program
{
static void Main(string[] args)
{
string text = "Hello. This is First Line \nHello. This is Second Line \nHello. This is Third
Line";
//Writing string into StringBuilder
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new StringWriter(stringBuilder);
//Store Data on StringBuilder
stringWriter.WriteLine(text);
stringWriter.Flush();
stringWriter.Close();
//Read Entry
StringReader reader = new StringReader(stringBuilder.ToString());
//Check to End of File
while (reader.Peek() > -1)
{
Console.WriteLine(reader.ReadLine());
}
Console.ReadKey();
}
}
}
Output:

Note: Being a derived class of the TextWriter class, the StringWriter class is used for writing
and dealing with the string data instead of the files with the purpose to manipulate the string
data and storing the result into the StringBuilder.

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.
Let us understand the constructors, and methods of StringReader class in C#.

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.

Example to Understand StringReader Class in C#:

In the below example, the StringReader class reads a string from a string variable and marks
each line with the count number, and then displays it on the console.

using System;
using System.IO;
namespace StringWriter_StringReader_Demo
{
class Program
{
static void Main(string[] args)
{
string text = @"You are reading
this StringWriter and StringReader in C# article at
dotnettutorials.net";
using (StringReader rtringReader = new StringReader(text))
{
int count = 0;
string line;
while ((line = rtringReader.ReadLine()) != null)
{
count++;
Console.WriteLine("Line {0}: {1}", count, line);
}
}
Console.ReadKey();
}
}
}

Output:
FileInfo Class in C# with Examples

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 the file. 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 FileInfo class, you will see the following.

The FileInfo class in C# provides the following Constructor, Methods, and Properties to work
with files.

The Constructor of FileInfo Class in C#

The FileInfo Class provides the following Constructor

public FileInfo(string fileName)

It is used to initialize 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 is used to get 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 that determines if 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 the file does not exist or if the file is a directory.
7. 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 the file does not exist or if
the file is a directory.
2. public FileInfo CopyTo(string destFileName): This method is used to copy an existing
file to a new file, disallowing the overwriting of an existing file. 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 file, allowing the overwriting of an existing file. 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 is used to create and return a new file.
5. public StreamWriter CreateText(): This method is used to create a StreamWriter that
writes a new text file.
6. public void Decrypt(): This method is used to decrypt a file that was encrypted by the
current account using the System.IO.FileInfo.Encrypt method.
7. public override void Delete(): This method is used to 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 is used to move 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 is used to open 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 and access, and unshared.
13. public FileStream Open(FileMode mode, FileAccess access, FileShare share): This
method is used to open 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, and 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 is used to create and returns a new read-
only System.IO.FileStream.
15. public StreamReader OpenText(): This method is used to create
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 is used to create 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 is used to return the path as a string.

Create a File in C# using FileInfo:

The Create method of FileInfo class is used to create the new file. For a better understanding,
please have a look at the below code. In the below code, we call the Create method on the
instance of FileInfo class which will create the MyTestFile1.txt file in the D drive.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\MyTestFile1.txt";
FileInfo fileInfo = new FileInfo(path);
fileInfo.Create();
{
Console.WriteLine("File has been created");
}
Console.ReadKey();
}
}
}

FileInfo Class CreateText Method in C#:

This method is used to create a StreamWriter that writes a new text file. For a better
understanding, please have a look at the below code.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\MyTestFile2.txt";
FileInfo fileInfo = new FileInfo(path);
StreamWriter str = fileInfo.CreateText();
str.WriteLine("Hello");
Console.WriteLine("File has been created with text");
str.Close();
Console.ReadKey();
}
}
}
FileInfo Class Delete Method in C#:

This method is used to delete an existing file. For a better understanding, please have a look at
the below code.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\MyTestFile2.txt";
FileInfo fileInfo = new FileInfo(path);
fileInfo.Delete();
Console.WriteLine("File has been deleted");
Console.ReadKey();
}
}
}

FileInfo Class CopyTo Method in C#:

This method is used to copy an existing file into a new file. For a better understanding, please
have a look at the below code. Here, MyTestFile1.txt should exist in the D drive and
MyTestFile2.txt should not exist in the D drive, otherwise, it will not work.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string path1 = @"D:\MyTestFile1.txt";
string path2 = @"D:\MyTestFile2.txt";

FileInfo fileInfo1 = new FileInfo(path1);


FileInfo fileInfo2 = new FileInfo(path2);
fileInfo1.CopyTo(path2);

Console.WriteLine("{0} was copied to {1}.", path1, path2);


Console.ReadKey();
}
}
}

FileInfo Class MoveTo Method in C#:

This method is used to move the file from one place to another valid location. For a better
understanding, please have a look at the below code. Here, sourcePath must exist and the
Dotnet folder should be there, otherwise it will not work.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string sourcePath = @"D:\MyTestFile1.txt";
string destinationPath = @"D:\Dotnet\MyTestFile1.txt";
FileInfo fileInfo = new FileInfo(sourcePath);
fileInfo.MoveTo(destinationPath);
Console.WriteLine("{0} was moved to {1}.", sourcePath, destinationPath);
Console.ReadKey();
}
}
}

FileInfo Class AppendText Method in C#:

The FileInfo Class AppendText Method in C# creates a StreamWriter that appends text to the
file represented by this instance of the FileInfo. For a better understanding, please have a look
at the below code.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string Path = @"D:\MyTestFile1.txt";
FileInfo fileInfo = new FileInfo(Path);
StreamWriter streamWriter = fileInfo.AppendText();
streamWriter.WriteLine("This");
streamWriter.WriteLine("is Extra");
streamWriter.WriteLine("Text");
Console.WriteLine("File has been appended");
streamWriter.Close();
Console.ReadKey();
}
}
}

FileInfo Class OpenText Method in C#:

The FileInfo Class OpenText Method in C# creates a StreamReader with UTF8 encoding that
reads from an existing text file. For a better understanding, please have a look at the below
code.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string Path = @"D:\MyTestFile1.txt";
FileInfo fileInfo = new FileInfo(Path);
StreamReader streamReader = fileInfo.OpenText();
string s = "";
while ((s = streamReader.ReadLine()) != null)
{
Console.WriteLine(s);
}

Console.ReadKey();
}
}
}

How to Get File Info in C#?

In the below example, I will show you the use of FileInfo class in C# to perform different types
of file operations. In the below example, we will search for the file D:\Dotnet\FileInfo1.txt file.
If the file is found then it displays the information of the file else create a new file. But you
should have a folder with the name Dotnet in the D drive. Otherwise, this program will not
work.

using System;
using System.IO;
namespace FileInfoDemo
{
class Program
{
static void Main(string[] args)
{
string filePath = @"D:\Dotnet\FileInfo1.txt";
FileInfo fileInfo = new FileInfo(filePath);
//Create File
using (StreamWriter sw = fileInfo.CreateText())
{
sw.WriteLine("Hello FileInfo Class");
}
//Display File Info
Console.WriteLine("File Created on : " + fileInfo.CreationTime);
Console.WriteLine("Directory Name : " + fileInfo.DirectoryName);
Console.WriteLine("Name of File : " + fileInfo.Name);
Console.WriteLine("Full Name of File : " + fileInfo.FullName);
Console.WriteLine("Length of File : " + fileInfo.Length);
Console.WriteLine("Is Readonly : " + fileInfo.IsReadOnly);
Console.WriteLine("File is Last Accessed on : " + fileInfo.LastAccessTime);
//Deleting File
Console.WriteLine("Press small y for delete this file");
try
{
char ch = Convert.ToChar(Console.ReadLine());
if (ch == 'y')
{
if (fileInfo.Exists)
{
fileInfo.Delete();
Console.WriteLine(filePath + " Deleted Successfully");
}
else
{
Console.WriteLine("File doesn't exist");
}
}
}
catch
{
Console.WriteLine("Press Anykey to Exit...");
}
Console.ReadKey();
}
}
}
Output:
DirectoryInfo Class in C# with Examples

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 only focuses on the Directory, not on the file systems. So,
when we talk about the DirectoryInfo class, it means we are talking about the physical
directory, and with the help of it, we get the object with which we can create, delete, and also,
we can make some subdirectory and many more operations can be performed.

It provides several methods to perform operations related to directory and subdirectory. It is a


sealed class and hence it cannot be inherited. If you go to the definition of DirectoryInfo class,
you will see the following.

The DirectoryInfo class in C# provides the following constructor, methods, and properties to
work with the directory and subdirectory.

The Constructor of DirectoryInfo Class in C#

The DirectoryInfo class provides the following Constructor

public DirectoryInfo(string path)


It is used to initialize a new instance of the DirectoryInfo class on the specified path. Here, the
variable path specifies the path on which 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 is used to create a directory
using a DirectorySecurity object. The directorySecurity parameter specifies the access
control to apply to the directory.
3. CreateSubdirectory(string path): This method is used to create a subdirectory or
subdirectories 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 is
used to create 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 parameter recursive
specifies true to delete this directory, its subdirectories, and all files; otherwise, 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 collection of file information 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 is used to move 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 was passed by the user.

Create a new directory in C#:

The Create method of the DirectoryInfo is used to create a new directory. In the below
example, we are creating a folder called MyTestFile1 in the D Drive.

using System;
using System.IO;
namespace DirectoryInfoDemo
{
class Program
{
static void Main(string[] args)
{
String path = @"D:\MyTestFile1";
DirectoryInfo fl = new DirectoryInfo(path);
fl.Create();
{
Console.WriteLine("Directory has been created");
}
Console.ReadKey();
}
}
}
Once you execute the above code, you verify the folder in the D drive of your machine.

Create SubDirectory in C#

The CreateSubdirectory method of DirectoryInfo class is used to create a subdirectory or


subdirectories on the specified path. In the below example, we are creating a folder called
MyTestFile2 inside the MyTestFile1 folder.

using System;
using System.IO;
namespace DirectoryInfoDemo
{
class Program
{
static void Main(string[] args)
{
String path = @"D:\MyTestFile1";
DirectoryInfo fl = new DirectoryInfo(path);
DirectoryInfo dis = fl.CreateSubdirectory("MyTestFile2");
{
Console.WriteLine("SubDirectory has been created");
}
Console.ReadKey();
}
}
}
Move a Directory in C#

The MoveTo method of DirectoryInfo class in C# moves a directory to a new location including
its contents. In the below example, we are moving the MyTestFile1 directory inside the
NewTestFile1 directory.

using System;
using System.IO;
namespace DirectoryInfoDemo
{
class Program
{
static void Main(string[] args)
{
String path1 = @"D:\MyTestFile1";
string path2 = @"D:\NewTestFile1";
DirectoryInfo directoryInfo1 = new DirectoryInfo(path1);
DirectoryInfo directoryInfo2 = new DirectoryInfo(path2);
directoryInfo1.MoveTo(path2);
{
Console.WriteLine("Directory has been Moved");
}
Console.ReadKey();
}
}
}
Delete a directory in C#

The Delete method of DirectoryInfo class in C# is used to delete a directory, specifying whether
to delete subdirectories and files. In the below example, we ate deleting the NewTestFile1
directory from the D drive.

using System;
using System.IO;
namespace DirectoryInfoDemo
{
class Program
{
static void Main(string[] args)
{
string path = @"D:\NewTestFile1 ";
DirectoryInfo directoryInfo1 = new DirectoryInfo(path);
directoryInfo1.Delete();
{
Console.WriteLine("Directory has been deleted");
}
Console.ReadKey();
}
}
}
How do I get directory details in C#?

The following example shows the use of DirectoryInfo class in C#. In the below example, we
check for a directory “D:\Dotnet” and if then the directory will be there in the system. it will
show the directory information else it will create a new directory D:\Dotnet.

using System;
using System.IO;
namespace DirectoryInfoDemo
{
class Program
{
static void Main(string[] args)
{
string DirectoryPath = @"D:\Dotnet";
DirectoryInfo directoryInfo = new DirectoryInfo(DirectoryPath);
try
{
if (directoryInfo.Exists)
{
Console.WriteLine("{0} Directory is already exists", DirectoryPath);
Console.WriteLine("Directory Name : " + directoryInfo.Name);
Console.WriteLine("Path : " + directoryInfo.FullName);
Console.WriteLine("Directory is created on : " + directoryInfo.CreationTime);
Console.WriteLine("Directory is Last Accessed on " + directoryInfo.LastAccessTime);
}
else
{
directoryInfo.Create();
Console.WriteLine(DirectoryPath + "Directory is created successfully");
}
//Delete this directory
Console.WriteLine("If you want to delete this directory press small y. Press any key to
exit.");
try
{
char ch = Convert.ToChar(Console.ReadLine());
if (ch == 'y')
{
if (directoryInfo.Exists)
{
directoryInfo.Delete();
Console.WriteLine(DirectoryPath + "Directory Deleted");
}
else
{
Console.WriteLine(DirectoryPath + "Directory Not Exists");
}
}
}
catch
{
Console.WriteLine("Press Enter to Exit");
}
Console.ReadKey();
}
catch (DirectoryNotFoundException d)
{
Console.WriteLine("Exception raised : " + d.Message);
Console.ReadKey();
}
}
}
}
Once you run the above code, you will get the following output. Notice, that this directory
does not exist and hence it will create the directory.
Now, press any key except y and close the program and run again. As the directory
was already created in the first run, this time you will get the following output.

You might also like