If you are working with C# files, then you may want to clear contents of a text file before writing new data in it, so in this article, I have mentioned how we can clear text file or delete file in C# with console application example.

Clear Text file Contents in C#

There are multiple ways to clear text file contents using C#, before writing a new text in it programmatically, so here is an example text file, with some sample data in it as shown in image.

clear-text-file-in-C#-sample-file

Now to delete text file contents in C# we will write empty text in file, here is the code

using System;
using System.IO;

namespace ClearContentCsharp
{
    public class Program
    {
        static void  Main(string[] args)
        {
            var path = @"D:\SampleTextFile.txt";
            File.WriteAllText(path, String.Empty);
            Console.WriteLine("File Contents are empty");
        }

    }
}

Output:

File Contents are empty

Now, if you will open text file again and check, you will find all text content is truncated and it will be empty.

OR

You can also use the open file in FileMode.Truncate as shown below

using (var fs = new FileStream(@"D:\SampleTextFile.txt", FileMode.Truncate))
{
   //add new contents in file
}

The above code will open the file and delete all the contents inside it, then you can add new content to it.

Delete File in C#

If you want to completely remove or delete the file using C#, then the code is a little bit different than above.

We will have to first verify if the file exists or not(using File.Exists()), at a specified location, if yes, then we can use File.Delete(path) method to delete the file.

Here is the complete code example

using System;
using System.IO;

namespace ClearContentCsharp
{
    public class Program
    {
        static void  Main(string[] args)
        {
            //file path
            var path = @"D:\SampleTextFile.txt";
            //check if file exists
            if (File.Exists(path))
            {
                Console.WriteLine("Deleting File");

                //delete file
                File.Delete(path);
            }
        }

    }
}

Output:

Deleting file

Once the above code is executed, "SampleTextFile" is deleted from the location "D:\SampleTextFile.txt".

In the above code, File class in the System.IO namespace provides the Delete() method to delete a file in C#.

You may also like to read:

Iterate Over Dictionary in C# (Various ways)

Create text file in C#

Remove last character from string in C#

Merge Sort in C#

Fibonacci series In C# (Various possible ways)

System.Text.Json Serialize / Deserialize Object in C#

Fallback image in HTML

C# Split String into array