In ane of the previous article, nosotros have mentioned, How to get file extension or file size in C# ? ( Code With Example ), simply in this mail, 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 bones 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 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 bones example of creating a file in C# using File class, first nosotros will check if the file exists using File.Exists, if non create it using File.Create

          class Programme     {         static void Principal(string[] args)         {             //path of file             string pathToFile = @"Eastward:\C-sharp-IO\test.txt";              //Create if information technology doesn't exists             if (File.Exists(pathToFile))             {                 //shows bulletin if examination file exist                  Console.WriteLine("Yep it exists");             }             else             {                 //create the file test.txt                  File.Create(pathToFile);                 Console.WriteLine("File 'test' created");                              }          }     }        

Executing the above line your console application volition requite you output equally beneath (I take already created Binder with proper name C-sharp-IO in my PC's E: drive and IIS_Users take full rights to edit, read, create, delete information technology.)

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

When You will navigate to the path which nosotros have given in our console app, yous tin find the file is created with name test but information technology is empty.

file-created-using-csharp.png

Calculation Data to File using C#

Now, suppose you need to add some data in the using C# lawmaking programmatically you lot can exercise it using Organisation.IO.TextWriter, at that place are other ways also to practise information technology, but first we will be checking example using TextWriter.

Some of the main members of the abstract grade TextWriter.

  • close() -- Closes the Author 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

          class Program     {         static void Main(cord[] args)         {             //path of file             string pathToFile = @"E:\C-precipitous-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.Shut();             }             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 but had to add lines in the txt file and information technology was done using TextWriter .

Write to a file with StreamWriter in C#

If you want to change the above lawmaking for writing in to file and add together some lines using StreamWriter class using C#, information technology will exist done every bit beneath

          StreamWriter writer = new StreamWriter(pathToFile); writer.WriteLine("File I/O in C# on qa with experts"); author.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, so for that either you tin 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 abstruse class TextReader.

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

Now, we can create the console awarding 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             cord pathToFile = @"E:\C-sharp-IO\examination.txt";              //Create if it doesn't exists             if (File.Exists(pathToFile))             {                 //Aye file exists                 //go file and create TextReader object                 TextReader tr = new StreamReader(pathToFile);                                  Console.WriteLine(tr.ReadLine());                  Panel.WriteLine(tr.ReadLine());                 Console.WriteLine(tr.ReadLine());                  tr.Close();             }             else             {                 //create the file test.txt                  File.Create(pathToFile);                 Console.WriteLine("File 'test' created");                              }          }     }        

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

And then, changing the above plan's lawmaking

                      class Programme     {         static void Master(cord[] args)         {             //path of file             string pathToFile = @"E:\C-sharp-IO\exam.txt";              //Create if it doesn't exists             if (File.Exists(pathToFile))             {                 //Yes file exists                 //become 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 'examination' 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"); Panel.WriteLine(file);        

Reading lines using StreamReader in C#

          class Program     {         static void Main(cord[] args)         {             //path of file             cord 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()) != naught)                     {                         // Do something with the line.                          Console.WriteLine(line);                     }                 }             }             else             {                 //create the file test.txt                  File.Create(pathToFile);                 Panel.WriteLine("File 'test' created");                              }          }     }        

As method StreamReader, Information technology returns null if no further data is available in the file,so we tin can use loop all lines of text file until nada information 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.Re-create in C#

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

          form Program     {         static void Primary(string[] args)         {             //path of file             string pathToOriginalFile = @"E:\C-sharp-IO\test.txt";                           //duplicate file path              string PathForDuplicateFile = @"E:\C-abrupt-IO\testDuplicate.txt";                             //provide source and destination file paths             File.Copy(pathToOriginalFile, PathForDuplicateFile);              Console.ReadKey();          }     }        

Executing the in a higher place code volition create a new file in the destination file location, as beneath

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.

          course Program     {         static void Main(string[] args)         {            //Go 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 in a higher place will delete the indistinguishable file we created earlier.

Check if Exists and and then Delete

Information technology is ever expert practice to check if file exists and then delete it, otherwise if file doesn't exists, then higher up case code may throw fault and program tin be halted from executing further.

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

          class Program     {         static void Chief(string[] args)         {            //Get Location of file to delete             string LocToDeleteFile = @"East:\C-sharp-IO\testDuplicate.txt";                         //check if file exists before deleting information technology             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 employ specialized classes to operate on it as described above. In the general case, notwithstanding, a file is but an assortment of bytes.The most general manner to read and write files is using the Stream form

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

          class Program     {         static void Main(string[] args)         {             cord 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.Shut();          }     }        

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

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

The downside to calling Stream'south Read() and Write() methods is that these disk operations are just performed when explicitly stated.

So, this is where we can use buffered streams, which make up one's mind how much data to read and write to the disk and whenUsing the BufferedStream class makes reads and writes more efficient.

Since it may accept already fetched more information from disk than previously requested, a Read() might but accept to read in-retentiveness data instead of going to the disk.

Above program in the buffered stream would be every bit below

          course 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.Affluent();             bostream.Shut();          }     }        

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

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