Udostępnij za pośrednictwem


How to: Delete a File in Visual Basic

The DeleteFile method of the My.Computer.FileSystem object allows you to delete a file. Among the options it offers are: whether to send the deleted file to the Recycle Bin, whether to ask the user to confirm that the file should be deleted, and what to do when the user cancels the operation.

To delete a text file

  • Use the DeleteFile method to delete the file. The following code demonstrates how to delete the file named test.txt.

    My.Computer.FileSystem.DeleteFile("C:\test.txt")
    

To delete a text file and ask the user to confirm that the file should be deleted

  • Use the DeleteFile method to delete the file, setting showUI to AllDialogs. The following code demonstrates how to delete the file named test.txt and allow the user to confirm that the file should be deleted.

    My.Computer.FileSystem.DeleteFile("C:\test.txt", _
            Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, _
            Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently, _
            Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
    

To delete a text file and send it to the Recycle Bin

  • Use the DeleteFile method to delete the file, specifying SendToRecycleBin for the recycle parameter. The following code demonstrates how to delete the file named test.txt and send it to the Recycle Bin.

    My.Computer.FileSystem.DeleteFile("C:\test.txt", _
    Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, _
    Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin)
    

Robust Programming

The following conditions may cause an exception:

See Also

Tasks

How to: Get the Collection of Files in a Directory in Visual Basic

How to: Delete a Directory in Visual Basic

Reference

UICancelOption Enumeration

My.Computer.FileSystem Object

UIOption Enumeration

RecycleOption Enumeration