blog

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

File I/O in C#

priyanka kushwaha2392 12-Mar-2015

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


Example:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.IO;

namespace FileIOExample

{

    classProgram

    {

        staticvoid Main(string[] args)

        {

            //To create a directory

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

            //To create a sub directory

            dir.CreateSubdirectory("Dotnet");

            //To create a Sample.txt

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

            StreamWriter sw=file.CreateText();

            sw.WriteLine("Sample file creation");

           sw.Close();

            StreamReader sr=file.OpenText();

            Console.Write(sr.ReadToEnd());

            if (dir.Exists)

            {

                DirectoryInfo[] dirs = dir.GetDirectories();

                foreach (object dirname in dirs)

                Console.WriteLine(dirname.ToString());

            }

            Console.ReadKey();

        }

    }

}

 
Output:

Sample file creation

Dotnet


Updated 22-Feb-2018

Leave Comment

Comments

Liked By