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

A file is a drove 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 divers in the Organisation.IO namespace. The basic file I/O class is FileStream, File I/O in C# is simpler equally compared to other programming languages like C++.

The Organization.IO namespace has various classes that are used for performing numerous operations with files, such equally 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 commencement'due south with the basic case of creating a file in C# using File grade, first nosotros will cheque if the file exists using File.Exists, if not create it using File.Create

          form Program     {         static void Chief(string[] args)         {             //path of file             string pathToFile = @"Due east:\C-sharp-IO\test.txt";              //Create if it doesn't exists             if (File.Exists(pathToFile))             {                 //shows bulletin if test file exist                  Console.WriteLine("Yeah it exists");             }             else             {                 //create the file examination.txt                  File.Create(pathToFile);                 Console.WriteLine("File 'test' created");                              }          }     }        

Executing the in a higher place line your console application will requite you lot output as below (I have already created Folder with name C-precipitous-IO in my PC's Due east: bulldoze and IIS_Users have total rights to edit, read, create, delete it.)

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

When You will navigate to the path which we take given in our panel app, you can find the file is created with proper noun exam but information technology is empty.

file-created-using-csharp.png

Adding Data to File using C#

Now, suppose you demand to add together some data in the using C# lawmaking programmatically yous can practise it using Organization.IO.TextWriter, there are other means besides to do it, but beginning we will exist checking example using TextWriter.

Some of the master members of the abstract grade TextWriter.

  • shut() -- Closes the Writer and frees any associated resource.
  • 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

          grade Program     {         static void Main(string[] args)         {             //path of file             string pathToFile = @"E:\C-abrupt-IO\test.txt";              //Create if it doesn't exists             if (File.Exists(pathToFile))             {                 //Yeah 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.Affluent();                 writeFile.Shut();             }             else             {                 //create the file test.txt                  File.Create(pathToFile);                 Panel.WriteLine("File 'test' created");                              }          }     }        

Output:

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

As the file was already created, we only had to add together lines in the txt file and information technology was done using TextWriter .

Write to a file with StreamWriter in C#

If you desire to change the in a higher place code for writing in to file and add some lines using StreamWriter class using C#, it will exist 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 demand to read text information from files, and so for that either you lot tin use TextReader or StreamReader and read the file line by line, suppose we take this text in our file

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

Some of the chief 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 equally a string.
  • ReadToEnd() -- Reads all characters to the end of the TextReader and returns them equally one string.

At present, nosotros can create the panel application for reading higher up lines using C#.

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

C# Read From File with TextWriter

          form 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);                 Panel.WriteLine("File 'test' created");                              }          }     }        

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

Then, irresolute the to a higher place plan's code

                      class Program     {         static void Main(string[] args)         {             //path of file             string pathToFile = @"Due east:\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 examination.txt                  File.Create(pathToFile);                 Console.WriteLine("File 'examination' created");                              }          }     }        

Output:

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

Read Everything From File with ReadAllText Part in C#

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

Reading lines using StreamReader in C#

          form Program     {         static void Main(cord[] args)         {             //path of file             string pathToFile = @"Eastward:\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)                     {                         // Practice something with the line.                          Console.WriteLine(line);                     }                 }             }             else             {                 //create the file test.txt                  File.Create(pathToFile);                 Console.WriteLine("File 'examination' created");                              }          }     }        

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

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

Copying File using File.Re-create in C#

In that location may exist a demand in your C# program to copy the file, information technology can be done easily using C# method File.Copy(sourceFileLoc,destFileLoc), you but need to provide source file and destination file location, hither is the simple program demonstrating the usage of information technology.

          class Plan     {         static void Master(string[] args)         {             //path of file             string pathToOriginalFile = @"E:\C-precipitous-IO\exam.txt";                           //duplicate file path              string PathForDuplicateFile = @"E:\C-sharp-IO\testDuplicate.txt";                             //provide source and destination file paths             File.Re-create(pathToOriginalFile, PathForDuplicateFile);              Console.ReadKey();          }     }        

Executing the above code will create a new file in the destination file location, equally 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 Primary(string[] args)         {            //Become Location of file to delete             string LocToDeleteFile = @"Eastward:\C-sharp-IO\testDuplicate.txt";            //call File.Delete with location of file             File.Delete(LocToDeleteFile);              Console.ReadKey();          }     }        

Executing the above volition delete the duplicate file nosotros created earlier.

Bank check if Exists and then Delete

It is e'er good do to check if file exists so delete information technology, otherwise if file doesn't exists, then higher up example code may throw error and program can be halted from executing farther.

Then hither is the higher up updated code, to bank check if file exists, if yeah, and then delete it.

          grade Programme     {         static void Chief(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 tin use specialized classes to operate on it as described above. In the general instance, however, a file is just an array of bytes.The most general way to read and write files is using the Stream form

We will expect at an case that copies the contents of i file to another.

          class Programme     {         static void Main(string[] args)         {             string dir = @"E:\C-abrupt-IO";             Stream istream =             File.OpenRead(dir + @"\test.txt");             Stream ostream =             File.OpenWrite(dir + @"\testfile2.txt");             byte[] buffer = new byte[1024];                          //get all the information 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.Shut();          }     }        

Executing the above Code in Visual Studio will create some other 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 verbal number of bytes to manipulate at a time.

The downside to calling Stream's Read() and Write() methods is that these deejay operations are merely performed when explicitly stated.

So, this is where nosotros can use buffered streams, which decide how much data to read and write to the disk and whenUsing the BufferedStream course makes reads and writes more efficient.

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

Higher up programme in the buffered stream would be as below

          class Program     {         static void Main(string[] args)         {             cord dir = @"East:\C-precipitous-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();          }     }        

Detect the phone 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.

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