Home > DeveloperSection > Blogs > File I/O in C#

File I/O in C#

.NET C# 
0 Comment(s)
 796  View(s)
Rate this:

File I/O in C#

In this blog, I’m explaining about File I/O in C#

The .NET framework provides a group of classes and methods in the System.IO namespace to allow synchronous and asynchronous reading from and writing to data streams and files. It includes following classes :

·         Directory

·         DirectoryInfo

·         FileInfo

·         FileStream


1.       Directory: Contains static methods to create, move and enumerate directories and subdirectories. The static method of the directory class do a security check on all methods.

2.       DirectoryInfo : Contains instance methods to create, move and enumerate directories and subdirectories. If you want to reuse an object multiple times, use DirectoryInfo instead of Directory to avoid security checks.

3.       FileInfo: Contains instance methods to create, copy, delete, move and open files and assists in the creation of FileStream objects. Use FileInfo if you want to reuse the File instance on a single file.

4.       FileStream: Provides implementations for the abstract stream class suitable for file-based streaming (random file access).  The FileStream class can open a file in one of the two modes either synchronously (read and write methods) or asynchronously (BeginRead and BeginWrite methods).


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.IO;

namespace FileIOExample


    class Program


        static void Main(string[] args)


            //To create a directory

            DirectoryInfo dir = new DirectoryInfo("c:\\FileIO");

            //To create a sub directory


            //To create a Sample.txt

               FileInfo file = new FileInfo(@"c:\\FileIO\Dotnet\Sample.txt");

            StreamWriter sw=file.CreateText();

            sw.WriteLine("Sample file creation");


            StreamReader sr=file.OpenText();


            if (dir.Exists)


                DirectoryInfo[] dirs = dir.GetDirectories();

                foreach (object dirname in dirs)









Sample file creation


Don't want to miss updates? Please click the below button!

Follow MindStick