CLOSE

   C# Tutorial  C# File Handling  C#  
   Technology    Programming

C# File Handling

         
 JANUARY 5, 2020   by shubhamrdarda

The objective of this article is to understand the concept of file handling operations using predefined classes and methods in C# language. The file handling operations include reading, writing, appending, etc. data to a file, and these operations carried out one by one. Firstly, we will see an implementation of how to create a text file, and in the subsequent section of this article, we will see how to manipulate a file by performing the various file operations.


Introduction to C# File Handling:

A file is a collection of data or information stored in disk with a specific name and directory path. The created file has properties like the date (when it got created), size, path (where it saved), etc. When you read or write the data to a file, then it becomes a stream. Here stream means, a communication medium through which the sequence of byte passes. The file operation like reading, where we read the data from a file, writing, where we write to a file by removing the existing content, and in appending, we write to a file by keeping the existing data and add new data at the end of a file. C# supports file handling through the classes in the System.IO namespace. This namespace contains types that allow reading and writing to files and data streams. Following is the list of classes and its description.

Classes Description
BinaryReader It reads primitive data from a binary stream
BinaryWriter It writes primitive data in binary to a stream
BufferedStream It is temporary storage for a stream of bytes
Directory It is used to manipulate a directory structure
DirectoryInfo It is used to perform operations on directories
DriveInfo It provides information for the drives
File It is used to manipulate files
FileInfo It is used to perform operations on files
FileStream It is used to read from and write data to a file
MemoryStream It is used for random access to streamed data stored in memory
Path It is used to perform the operations on path information
StreamReader It is used for reading characters from a byte stream
StreamWriter It is used for writing characters to a stream
StringReader It is used for reading from a string buffer
StringWriter It is used for writing into a string buffer



C#: Creating an empty file

Let's see an implementation of how to create an empty text file.

Filename: Program.cs

using System;
using System.IO;

namespace Studytonight
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath = @"D:\textfile.txt";
            File.Create(filepath);
            Console.WriteLine("A text file created successfully.");
        }
    }
}

Output:

A text file created successfully.

In this example, the File is a class, and Create() is a method that we used to create a text file. Firstly, we have stored the file path in a string variable using a verbatim identifier (@). The verbatim string literal used to embed filename, path, and regular expression in the source code. In the Create method, we have provided the path to create a text file at that location. The following example shows how to delete a file if it exists in the same location, which defined in source code.




C#: Deleting a file

Let's see the implementation of how to delete a file if exist at a specified location.

Filename: Program.cs

using System;
using System.IO;

namespace Studytonight
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath = @"D:\textfile.txt";
            if(File.Exists(filepath))
            {
                File.Delete(filepath);
                Console.WriteLine("Existing Text File Deleted.");
            }
            File.Create(filepath);
            Console.WriteLine("New Text file created successfully.");
        }
    }
}

Output:

Existing Text File Deleted.
New Text file created successfully.

In the prior example, we have created a text file in D drive, and in this example, we are checking the presence of the same file that exists at the specified location or not. The if condition will return true in our case hence the Delete method will remove the text file and print the desired output on the console. Once the control is out of the if block, then we are again creating a text file on the same path. The next example demonstrates how to write data in a text file.




C#: Writing text in a File

Let's an example of how to write data in a text file,

Filename: Program.cs

using System;
using System.IO;

namespace Studytonight
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath = @"D:\textfile.txt";
            if(File.Exists(filepath))
            {
                File.Delete(filepath);
                Console.WriteLine("Existing Text File Deleted.");
            }
            File.WriteAllText(filepath,"Writing this text to a file.");
            Console.WriteLine("Created a new text file and wrote the text in it.");
            Console.WriteLine(File.ReadAllText(filepath));
        }
    }
}

Output:

Existing Text File Deleted.
Created a new text file and wrote the text in it.
Writing this text to a file.

In this example again, we have deleted the text file at the specified location. Once the control is out of the if block, we are writing data to a text file using the WriteAllText method. The predefined WriteAllText method creates a new file irrespective of an existing file and writes the specified data into it. If we don't check the condition for a file with the same name is present on a specified path or not then the WriteAllText method replaces the old file with a new one by writing the data to it. Lastly, we are reading the data from the same file using the ReadAllText method.

Note: All the examples of file operation are easy once you are aware of all predefined classes and the ways to perform the operation on files.




C#: Appending text in a File

Let's take an example on append the data in an existing text file using StreamWriter class,

Filename: Program.cs

using System;
using System.IO;

namespace Studytonight
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath = @"D:\textfile.txt";
            try
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.Write(Environment.NewLine+"Appending this text in a file.");
                    sw.Close();
                }
            }
            catch(FileNotFoundException fnfe)
            {
                Console.WriteLine("File Not Found Exception: "+fnfe);
            }
            finally
            {
                Console.WriteLine(File.ReadAllText(filepath));
            }
        }
    }
}

Output:

Writing this text to a file.
Appending this text in a file.

In the above example, we have written the data to a text file using StreamWrite class, and in this example, we are appending data to an existing file by using the AppendText method. If you observe the preceding example, we have created an object of the StreamWriter class, and in the write method, we have used the Environment.NewLine property to append data on the next line of the same file. Also, we have used the exception handing concept to handle the unexpected situation like file not found. The try block contains the code where the possibility of an exception is possible, and the catch block handles the exception if it occurs in a try block. Lastly, we used the finally block, irrespective of try and catch block, the finally block of code always gets executed, and we are reading the data in finally block which we appended in a try block.

Note: It is unnecessary that the catch block always gets executed, it executes only when the exception occurs in a try block.




C#: Copy and Move a File

Let's take an example on how to copy and move a text file from one drive to another,

Filename: Program.cs

using System;
using System.IO;

namespace CW
{
    class Program
    {
        static void Main(string[] args)
        {
            string source = @"D:\textfile.txt";
            string destination = @"E:\textfile.txt";
            try
            {
                File.Move(source, destination);
                File.Copy(destination, source);
            }
            catch(FileNotFoundException fnfe)
            {
                Console.WriteLine(fnfe);
            }
        }
    }
}

In the above example, we have specified the source and destination for a file. So in the try block, we are moving a text file from D drive to E drive using the Move method. The Copy method on the other hand, copy the file from one location to another specified location while keeping the original file at the source location. These are the simple file operations we perform daily.




C#: Creating a new Directory

Let's see one last example on how to create a directory using Directory class

Filename: Program.cs

using System;
using System.IO;

namespace Studytonight
{
    class Program
    {
        static void Main(string[] args)
        {
            string dirpath = @"D:\ThisFolder";
            try
            {
                if (!Directory.Exists(dirpath))
                {
                    Directory.CreateDirectory(dirpath);
                    Console.WriteLine("Directory created successfully.");
                }
                else
                {
                    Console.WriteLine("Directory already exist.");
                }
            }
            catch(IOException ioe)
            {
                Console.WriteLine(ioe);
            }
        }
    }
}

Output:

Directory created successfully.

In the above example, firstly, we are checking the ThisFolder is already there or not. If it exists, then we are deleting the previous directory and creating a new one using Directory class at a specified location.




Conclusion:

We hope this article with lots of practical examples helped you to understand the concept of file handing in C# language. If you have any queries, then please let us know in the comment section. We are happy to solve your doubts.


SHARE YOUR THOUGHTS WITH US!