C# Delete File

To delete a file in C#, you can use System.IO.File.Delete(path) function. File.Delete() function deletes the file specified using the argument.

Example 1 – Delete File

In the following example, we shall delete a file with the path D:\sample.txt.

Program.cs

using System;
using System.IO;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            String path = @"D:\sample.txt";
            File.Delete(path);
            Console.WriteLine("Deleted file successfully.");
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Deleted file successfully.
ADVERTISEMENT

Note

If you try to delete a file that is not actually present using File.Delete(), no Exception is thrown or no error occurs.

Example 2 – Delete File with Path specified as null

If you specify path as null, System.ArgumentNullException is thrown by File.Delete() function.

Program.cs

using System;
using System.IO;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            String path = null;
            File.Delete(path);
            Console.WriteLine("Deleted file successfully.");
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: path
   at System.IO.File.Delete(String path)
   at CSharpExamples.Program.Main(String[] args) in D:\workspace\csharp\HelloWorld\Program.cs:line 8

Example 3 – Delete File – Path Containing Invalid Path Characters

The path should not contain invalid path characters. Invalid path characters’ numeric range is [0, 31] and 124. If path contains any of these invalid path characters, System.IO.IOException is thrown by File.Delete() function.

Program.cs

using System;
using System.IO;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            String path = "D:/sample1|.txt";
            File.Delete(path);
            Console.WriteLine("Deleted file successfully.");
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run

Unhandled Exception: System.IO.IOException: The filename, directory name, or volume label syntax is incorrect : 'D:\sample1|.txt'
   at System.IO.FileSystem.DeleteFile(String fullPath)
   at System.IO.File.Delete(String path)
   at CSharpExamples.Program.Main(String[] args) in D:\workspace\csharp\HelloWorld\Program.cs:line 8

Summary

In this C# Tutorial, we have learned to delete a file with the path specified.