Open In App

File.Delete() Method in C# with Examples

File.Delete(String) is an inbuilt File class method which is used to delete the specified file.
Syntax: 
 

public static void Delete (string path);

Parameter: This function accepts a parameter which is illustrated below: 
 



  • path: This is the specified file path which is to be deleted.

Exceptions:
 

Below are the programs to illustrate the File.Delete(String) method.
Program 1: Before running the below code, a file file.txt is created with some contents shown below:
 



 




// C# program to illustrate the usage
// of File.Delete(String) method
 
// Using System and System.IO namespaces
using System;
using System.IO;
 
public class GFG {
    // Using main() function
    public static void Main()
    {
        // Specifying a file
        String myfile = @"file.txt";
 
        // Calling the Delete() function to
        // delete the file file.txt
        File.Delete(myfile);
 
        // Printing a line
        Console.WriteLine("Specified file has been deleted");
    }
}

Executing: 
 

mcs -out:main.exe main.cs
mono main.exe
Specified file has been deleted

After running the above code, the above output is shown and the file file.txt has been deleted.
Program 2: Before running the below code, two files have been created shown below:
 

 

 




// C# program to illustrate the usage
// of File.Delete(String) method
 
// Using System and System.IO namespaces
using System;
using System.IO;
 
public class GFG {
    // Using main() function
    public static void Main()
    {
        // Specifying two files
        String myfile1 = @"file.txt";
        String myfile2 = @"gfg.txt";
 
        // Calling the Delete() function to
        // delete the file file.txt and gfg.txt
        File.Delete(myfile1);
        File.Delete(myfile2);
 
        // Printing a line
        Console.WriteLine("Specified files have been deleted.");
    }
}

Executing: 
 

mcs -out:main.exe main.cs
mono main.exe
Specified files have been deleted.

After running the above code, above output is shown and two existing files file.txt and gfg.txt have been deleted.
 


Article Tags :
C#