In one of the previous article, we have mentioned, How to get file extension or file size in C# ? ( Code With Example ), but in this post, we will check all file input ouput or file I/O operations in C#.

A file is a collection of data stored on a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.

In C#, I/O classes are defined in the System.IO namespace. The basic file I/O class is FileStream, File I/O in C# is simpler as compared to other programming languages like C++.

The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.

Creating a File programmatically in C# using System.IO

Let's start's with the basic example of creating a file in C# using File class, first we will check if the file exists using File.Exists, if not create it using File.Create

class Program
    {
        static void Main(string[] args)
        {
            //path of file
            string pathToFile = @"E:\C-sharp-IO\test.txt";

            //Create if it doesn't exists
            if (File.Exists(pathToFile))
            {
                //shows message if test file exist 
                Console.WriteLine("Yes it exists");
            }
            else
            {
                //create the file test.txt 
                File.Create(pathToFile);
                Console.WriteLine("File 'test' created");
                
            }

        }
    }

Executing the above line your console application will give you output as below (I have already created Folder with name C-sharp-IO in my PC's E: drive and IIS_Users have full rights to edit, read, create, delete it.)

file-create-if-not-exists-c-sharp.png

When You will navigate to the path which we have given in our console app, you can find the file is created with name test but it is empty.

file-created-using-csharp.png

Adding Data to File using C#

Now, suppose you need to add some data in the using C# code programmatically you can do it using System.IO.TextWriter, there are other ways also to do it, but first we will be checking example using TextWriter.

Some of the main members of the abstract class TextWriter.

  • close() -- Closes the Writer and frees any associated resources.
  • Write() -- Writes a line to the text stream, without a newline.
  • WriteLine() -- Writes a line to the text stream, with a newline.
  • Flush() -- Clears all buffers.

Writing in File using TextWriter

class Program
    {
        static void Main(string[] args)
        {
            //path of file
            string pathToFile = @"E:\C-sharp-IO\test.txt";

            //Create if it doesn't exists
            if (File.Exists(pathToFile))
            {
                //Yes file exists
                //create TextWriter object
                TextWriter writeFile = new StreamWriter(pathToFile);
                //write data into file
                writeFile.WriteLine("File I/O in C# on qa with experts");
                writeFile.Flush();
                writeFile.Close();
            }
            else
            {
                //create the file test.txt 
                File.Create(pathToFile);
                Console.WriteLine("File 'test' created");
                
            }

        }
    }

Output:

output-writing-file-using-c-sharp-programitically-min.png

As the file was already created, we just had to add lines in the txt file and it was done using TextWriter .

Write to a file with StreamWriter in C#

If you want to change the above code for writing in to file and add some lines using StreamWriter class using C#, it will be done as below

StreamWriter writer = new StreamWriter(pathToFile);
writer.WriteLine("File I/O in C# on qa with experts");
writer.Close();

Reading text lines from File in C#

Other than creating and adding text the in a file you may need to read text data from files, so for that either you can use TextReader or StreamReader and read the file line by line, suppose we have this text in our file

reading-text-lines-using-c-sharp-min.png

Some of the main members of the abstract class TextReader.

  • Read() -- Reads data from an input stream.
  • ReadLine() -- Reads a line of characters from the current stream and returns the data as a string.
  • ReadToEnd() -- Reads all characters to the end of the TextReader and returns them as one string.

Now, we can create the console application for reading above lines using C#.

You can read: Read file in C# (Text file .NET and .NET Core example)

C# Read From File with TextWriter

class Program
    {
        static void Main(string[] args)
        {
            //path of file
            string pathToFile = @"E:\C-sharp-IO\test.txt";

            //Create if it doesn't exists
            if (File.Exists(pathToFile))
            {
                //Yes file exists
                //get file and create TextReader object
                TextReader tr = new StreamReader(pathToFile);
                
                Console.WriteLine(tr.ReadLine());

                Console.WriteLine(tr.ReadLine());
                Console.WriteLine(tr.ReadLine());

                tr.Close();
            }
            else
            {
                //create the file test.txt 
                File.Create(pathToFile);
                Console.WriteLine("File 'test' created");
                
            }

        }
    }

You can notice that I am using Console.WriteLine(tr.ReadLine()) for each line to print, suppose you have no idea about how many lines are there in text file to read then you can use Console.WriteLine(tr.ReadToEnd()) which read's all the lines of files and return's it

So, changing the above program's code

 class Program
    {
        static void Main(string[] args)
        {
            //path of file
            string pathToFile = @"E:\C-sharp-IO\test.txt";

            //Create if it doesn't exists
            if (File.Exists(pathToFile))
            {
                //Yes file exists
                //get file and create TextReader object
                TextReader tr = new StreamReader(pathToFile);
                
                //read all lines of text file and print it
                Console.WriteLine(tr.ReadToEnd());
               
                tr.Close();
            }
            else
            {
                //create the file test.txt 
                File.Create(pathToFile);
                Console.WriteLine("File 'test' created");
                
            }

        }
    }

Output:

read-lines-using-textwriter-c-sharp2-min.png

Read Everything From File with ReadAllText Function in C#

string file = File.ReadAllText("C:\\file.txt");
Console.WriteLine(file);

Reading lines using StreamReader in C#

class Program
    {
        static void Main(string[] args)
        {
            //path of file
            string pathToFile = @"E:\C-sharp-IO\test.txt";

            //Create if it doesn't exists
            if (File.Exists(pathToFile))
            {
                // Read every line in the file.
                using (StreamReader reader = new StreamReader(pathToFile))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        // Do something with the line.

                        Console.WriteLine(line);
                    }
                }
            }
            else
            {
                //create the file test.txt 
                File.Create(pathToFile);
                Console.WriteLine("File 'test' created");
                
            }

        }
    }

As method StreamReader, It returns null if no further data is available in the file,so we can use loop all lines of text file until null data is returned and print each line as shown above output when executing it in Visual Studio

using-streamreader-for-reading-lines-in-c-sharp-min.png

Copying File using File.Copy in C#

There may be a need in your C# program to copy the file, it can be done easily using C# method File.Copy(sourceFileLoc,destFileLoc), you just need to provide source file and destination file location, here is the simple program demonstrating the usage of it.

class Program
    {
        static void Main(string[] args)
        {
            //path of file
            string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";

            
            //duplicate file path 
            string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";
             
              //provide source and destination file paths
            File.Copy(pathToOriginalFile, PathForDuplicateFile);

            Console.ReadKey();

        }
    }

Executing the above code will create a new file in the destination file location, as below

duplicate-file-using-file-copy-c-sharp.png

Deleting a file using File.Delete

File.Delete method is used to delete an existing file. Let's look at an example.

class Program
    {
        static void Main(string[] args)
        {
           //Get Location of file to delete
            string LocToDeleteFile = @"E:\C-sharp-IO\testDuplicate.txt";
           //call File.Delete with location of file
            File.Delete(LocToDeleteFile);

            Console.ReadKey();

        }
    }

Executing the above will delete the duplicate file we created earlier.

Check if Exists and then Delete

It is always good practice to check if file exists and then delete it, otherwise if file doesn't exists, then above example code may throw error and program can be halted from executing further.

So here is the above updated code, to check if file exists, if yes, then delete it.

class Program
    {
        static void Main(string[] args)
        {
           //Get Location of file to delete
            string LocToDeleteFile = @"E:\C-sharp-IO\testDuplicate.txt";
           
            //check if file exists before deleting it
            if(File.Exists(LocToDeleteFile))
            {
              //call File.Delete with location of file
              File.Delete(LocToDeleteFile );
            }

            Console.ReadKey();

        }
    }

In the above code, we are using File.Exists() to check if file exists or not, at specified location.

Binary I/O using Stream class

If we know that a particular file is text file, we can use specialized classes to operate on it as described above. In the general case, however, a file is just an array of bytes.The most general way to read and write files is using the Stream class

We will look at an example that copies the contents of one file to another.

class Program
    {
        static void Main(string[] args)
        {
            string dir = @"E:\C-sharp-IO";
            Stream istream =
            File.OpenRead(dir + @"\test.txt");
            Stream ostream =
            File.OpenWrite(dir + @"\testfile2.txt");
            byte[] buffer = new byte[1024];
            
            //get all the data in bytes
            int bytesRead = istream.Read(buffer, 0, 1024);
 
            //loop all the bytes
            while (bytesRead > 0)
            {
                // save data in new file
                ostream.Write(buffer, 0, bytesRead);
                bytesRead = istream.Read(buffer, 0, 1024);
            }
             //close both the streams
            istream.Close();
            ostream.Close();

        }
    }

Executing the above Code in Visual Studio will create another file(testfile2.text) with the same content as text.txt.

The Stream class gives complete control over how to access the file: where to read/write from, the exact number of bytes to manipulate at a time.

The downside to calling Stream’s Read() and Write() methods is that these disk operations are only performed when explicitly stated.

So, this is where we can use buffered streams, which decide how much data to read and write to the disk and when Using the BufferedStream class makes reads and writes more efficient.

Since it may have already fetched more data from disk than previously requested, a Read() might only have to read in-memory data instead of going to the disk.

Above program in the buffered stream would be as below

class Program
    {
        static void Main(string[] args)
        {
            string dir = @"E:\C-sharp-IO";
          
            Stream istream =
            File.OpenRead(dir + @"\test.txt");
            Stream ostream =
            File.OpenWrite(dir + @"\testfile2.txt");
            BufferedStream bistream = new BufferedStream(istream);
            BufferedStream bostream = new BufferedStream(ostream);
            byte[] buffer = new byte[1024];
            int bytesRead = bistream.Read(buffer, 0, 1024);
            while (bytesRead > 0)
            {
                bostream.Write(buffer, 0, bytesRead);
                bytesRead = bistream.Read(buffer, 0, 1024);
            }
            bistream.Close();
            bostream.Flush();
            bostream.Close();

        }
    }

Notice the call to Flush() on the output stream, since the buffered stream may not write the data to disk immediately, we need to explicitly make sure they have been written before we exit.

Move File in C#

To move file from one location to another we can use File.Move(from,to) method in C#

        var from = System.IO.Path.Combine(@"C:\folder\file.txt"); // old location
        var to = System.IO.Path.Combine(@"E:\folder\file.txt"); // new location

        File.Move(from, to); // Try to move

That's it hope it clear your basic concept all File IO and file handling in C#.