Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The System.IO Namespace
3.
File Operations
3.1.
Create File
3.2.
Delete a File
3.3.
Write in a File
3.4.
Copy and Move a File
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

File Handling In C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In this blog, we will learn about File Handling. It involves the management of files. A file is considered a collection of data stored in a disk with a name and a directory path. We can create, read, append and write to files in file handling. Above all mentioned operations, read and write are used most frequently. The File becomes stream when we open the File for writing and reading. A stream is a continuity of bytes that are used for communication.

Files have input as well as output streams that are used for reading and writing data, respectively.

The System.IO Namespace

In C#, The System.IO Namespace has various classes and types that allow reading and writing to files. Take a look at the table to get an idea of the essential classes

present in System.IO Namespace.

Classes Description
FileStream This class is Used to read from and write to any location in a file.
StreamReader This class is used for reading characters from a byte stream.
StreamWriter This class is used for writing characters to a stream.
BinaryReader This class is used in reading primitive data types in the form of binary values.
BinaryWriter This class is used to write primitive types in binary to a stream and supports writing strings in a specific encoding.
FileInfo This class provides us the properties and instance methods for the creation, copying, deletion, moving, and opening of files and aids in creating FileStream objects.
DirectoryInfo This class exposes instance methods for creating, moving, and enumerating through directories and subdirectories.
File This class helps in manipulating files.
StringReader

This class is used for reading from a string buffer.

 

StringWriter This class is used for writing into a string buffer.
Directory Helps in manipulating a directory structure.
DriveInfo Provides information for the drives.
MemoryStream Used to streamed data stored in memory for random access.
Path Performs operations on path information.
BufferedStream Used to create temporary storage for a stream of bytes.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

File Operations

Create File

In this example, we will learn how to create a text file using the File class and Create() method. At first, we store the file path in a string variable using a verbatim identifier (@). The verbatim string embeds filename, path, and regular expression in our code. We have given the path to creating a text file in the create method. 

using System;
using System.IO;


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

Output

A text file created successfully.

Delete a File

In the previous example, we learned to create a text file in D drive, and in this example, we first check the presence of the same File that exists at the specified location. If the condition returns true, we will use the Delete method to delete the text file and print the desired outcome on the console. The following example demonstrates how to delete a text file.

using System;
using System.IO;


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

Output

Existing Text File Deleted.

Write in a File

In the earlier example, we have deleted the text file present at a specific location. After the control is out of the if block, we write data to a text file using the WriteAllText method. The WriteAllText method creates a new file regardless of an existing file and writes the detailed data in it. The WriteAllText method overwrites the old File with a new one by writing the data to it if we don't cross-check the condition for a file with the same name on a specified path or not. Lastly, we read the same file data using the ReadAllText method.

using System;
using System.IO;


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

Output

Existing Text File Deleted.

wrote the text in it after creating a new text file

Writing this text in a file

 

Copy and Move a File

In the previous example, we have given the source and destination to a file. Hence in the try block, we move a text file from D drive to E drive using the Move method. The Copy method, on the other hand, copies the File from one location to another particular location while maintaining the original File at the source location. These are the simple file operations we perform daily.

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);
            }
        }
    }
}

Output

Existing Text File moved successfully from source to destination

 

Let’s move to the FAQ section to clear your minor doubts.

FAQs

  1. What is file handling in C#?
    File handling in C# refers to storing data as input or output produced by running C# programs in data files, namely, a text file or a binary file for future reference and analysis.
  2. Why do we use file handling in C#?
    File handling in C# helps us create, update, read, and delete the files stored on our local file system through our C# program.
  3. How do streams work in C#?
    In C# file operations, usually, streams are used to read and write to files. A stream is an additional layer created between an application and a file. The stream ensures smooth read and writes operations to the File. Streams usually are used when reading data from large files.
  4. What are I/O operations in C#?
    The System.IO namespace has various classes used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file, etc.
  5. What is the difference between FileStream and MemoryStream in C#?
    As the name suggests, a FileStream reads and writes to a file, whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored. 

Recommended Topic -  singleton design pattern in c#

Key Takeaways

In this article, we extensively discussed file handling in C#. We have seen some classes used in file handling operations. We have also learned various examples of creating a file, deleting a file, writing text to a file, etc. To read more about the c#, Visit Here.

We hope this blog has helped you enhance your knowledge regarding file handling in C#. In case you want to learn more, check out articles on Coding Ninjas Studio. Do upvote our blogs to help other ninjas grow. 

Happy Coding!

Live masterclass