FileInfo.Delete Method
Permanently deletes a file.
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| IOException |
The target file is open or memory-mapped on a computer running Microsoft Windows NT. -or- 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. |
| SecurityException |
The caller does not have the required permission. |
| UnauthorizedAccessException |
The path is a directory. |
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); try { using (StreamWriter sw = fi1.CreateText()) {} string path2 = path + "temp"; FileInfo fi2 = new FileInfo(path2); //Ensure that the target does not exist. fi2.Delete(); //Copy the file. fi1.CopyTo(path2); Console.WriteLine("{0} was copied to {1}.", path, path2); //Delete the newly created file. fi2.Delete(); 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. fs.Close(); // Delete the file. fi.Delete(); } }
-
FileIOPermission
for reading and writing files. Associated enumeration: FileIOPermissionAccess.Write
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.