Delete Method

FileInfo.Delete Method ()


Permanently deletes a file.

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)

public override void Delete()

Exception Condition

The target file is open or memory-mapped on a computer running Microsoft Windows NT.


There is an open handle on the file, and the operating system is Windows XP or earlier. This open handle can result from enumerating directories and files. For more information, see How to: Enumerate Directories and Files.


The caller does not have the required permission.


The path is a directory.

If the file does not exist, this method does nothing.


Delete does not delete a file that is open for normal I/O or a file that is memory-mapped.

The following example demonstrates the Delete method.

using System;
using System.IO;

class Test 

    public static void Main() 
        string path = @"c:\MyTest.txt";
        FileInfo fi1 = new FileInfo(path);

            using (StreamWriter sw = fi1.CreateText()) {}
            string path2 = path + "temp";
            FileInfo fi2 = new FileInfo(path2);

            //Ensure that the target does not exist.

            //Copy the file.
            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Delete the newly created file.
            Console.WriteLine("{0} was successfully deleted.", path2);

        catch (Exception e) 
            Console.WriteLine("The process failed: {0}", e.ToString());
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//c:\MyTest.txt was copied to c:\MyTest.txttemp.
//c:\MyTest.txttemp was successfully deleted.

The following example creates, closes, and deletes a file.

using System;
using System.IO;

public class DeleteTest 
    public static void Main() 
        // Create a reference to a file.
        FileInfo fi = new FileInfo("temp.txt");
        // Actually create the file.
        FileStream fs = fi.Create();
        // Modify the file as required, and then close the file.
        // Delete the file.

for reading and writing files. Associated enumeration: FileIOPermissionAccess.Write

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top
© 2015 Microsoft