File.Delete Method (String)
Deletes the specified file.
Assembly: mscorlib (in mscorlib.dll)
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
path is null.
The specified path is invalid (for example, it is on an unmapped drive).
The specified file is in use.
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.
path is in an invalid format.
The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
The caller does not have the required permission.
The file is an executable file that is in use.
path is a directory.
path specified a read-only file.
Specify a file name with any relative or absolute path information for the path parameter. Wildcard characters cannot be included. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
If the file to be deleted does not exist, no exception is thrown.
For a list of common I/O tasks, see Common I/O Tasks.
Delete does not delete a file that is open for normal I/O or a file that is memory mapped.
The following example copies groups of files to the C:\archives\2008 backup folder and then deletes them from the source folder.
Dim sourceDir As String = "c:\current" Dim backupDir As String = "c:\archives\2008" Try Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg") Dim txtList As String() = Directory.GetFiles(sourceDir, "*.txt") ' Copy picture files. For Each f As String In picList 'Remove path from the file name. Dim fName As String = f.Substring(sourceDir.Length + 1) ' Use the Path.Combine method to safely append the file name to the path. ' Will overwrite if the destination file already exists. File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True) Next ' Copy text files. For Each f As String In txtList 'Remove path from the file name. Dim fName As String = f.Substring(sourceDir.Length + 1) Try ' Will not overwrite if the destination file already exists. File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName)) ' Catch exception if the file was already copied. Catch copyError As IOException Console.WriteLine(copyError.Message) End Try Next For Each f As String In txtList File.Delete(f) Next For Each f As String In picList File.Delete(f) Next Catch dirNotFound As DirectoryNotFoundException Console.WriteLine(dirNotFound.Message) End Try
Available since 10
Available since 1.1
Available since 2.0
Windows Phone Silverlight
Available since 7.0