Introduction to File Handling Methods in C#


The File class belongs to System.IO namespace. It provides static methods to create, open, copy, delete or move the file.

The parent class of File is the Stream class. A stream is an abstract class. When you open a file for reading or writing purposes, it becomes a stream. Input and Output are two basic streams used for reading and writing respectively.

How to create and write to a file

The following snippet will check if the particular file exists, and if not, create one.

 string path = @"c:\MyFolder\MyFile.txt";
        if (!File.Exists(path){
            // create a file to write to.
            using (StreamWriter _streamWriter = File.CreateText(path)){
                _streamWriter.WriteLine("Hello World! ");
            }
         }

File.Exists(string path) will return true if the path contains the named file or returns false otherwise. Passing an invalid path will also return false. To check if the directory exists, use Directory.Exists(string path) instead.

File.CreateText(String path) will create or open a file for writing UTF-8 encoded text. If the file doesn’t exist, it will create one, otherwise, its content will be overwritten. You can achieve the same using StreamWriter(String, Boolean) with append parameter set to false.

How to read text from a file

Let’s say, you have created a file using above snippet and now want to read from it.

using (StreamReader _streamReader = File.OpenText(path)){
            string s;
            while ((s = _streamReader.ReadLine()) != null){
                Console.WriteLine(s);
            }
 }

Or you can also open the file using a stream reader.

using (StreamReader _streamReader = new StreamReader("file.txt")) {
                String line = _streamReader.ReadToEnd();
                Console.WriteLine(line);
}

The StreamReader class is inherited from the abstract class TextReader.

StreamReader.ReadToEnd() method reads all characters from the current position to the end of the stream. If the current position is already at the end of the stream, it will return an empty string.

StreamReader.Read() method will read the next character or the next set of characters.

StremReader.ReadLine() will read a line of characters and return data as a string.

How to delete a file

To delete a file, use File.Delete(string path) method. It would take the name with the absolute path to the file need to be deleted. If the file doesn’t exist, no exception is thrown.

string path = @"c:\MyFolder\MyFile.txt";
if (File.Exists(path){
            File.Delete(path);
 }

How to copy an existing file to a new file

The following snippet will copy an existing file to a new file using File.Copy(string source_file, string destination_file);

File.Copy("oldfile.txt", "newfile.txt");

There is also a third optional parameter that decides if u want to overwrite the existing file or not. Setting the third parameter as false, or leaving it from parameter list will not let you overwrite if the destination file already exists and will throw an IOException copyError.

To overwrite an existing file

File.Copy("oldfile.txt", "newfile.txt", true);

How to append text to a file

File.AppendText() method will append text to an existing file. Let’s understand this method with an example.

using System;
using System.IO;

class TPFileHandling
{
    public static void Main(){
        string path = @"d:\cfile.txt";
        if (!File.Exists(path)){
            // Create a file to write to.
            using (StreamWriter _streamWriter = File.CreateText(path)){
                _streamWriter.WriteLine("Hello World!");
            }	
        }
       // To append text
        using (StreamWriter _streamWriter = File.AppendText(path)) {
            _streamWriter.WriteLine("I am learning file handling methods in C#");
        }	

        // Open the file to read the text you just write and appended later. 
        using (StreamReader _streamReader = File.OpenText(path)) {
            string s = "";
            while ((s = _streamReader.ReadLine()) != null) {
                Console.WriteLine(s);
            }
        }
    }
}

How to replace the contents of a file with another

File.Replace(String, String, Boolean) method will replace the contents of a specified file with the content of another file. It will delete the original file while creating the backup of the replaced file.

string original_file = "file1.xml";
string file_to_replace = "file2.xml";
string backup_file = "file2.xml.bac";

File.Replace(original_file, file_to_replace, backup_file, false);

Related Articles

Insert Update Delete example in C# and VB.NET Using ExecuteNonQuery method

Socket connect and data send using C#

Auto-Complete ComboBox Using C#

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply