如何:在 Visual Basic 中删除文件How to: Delete a File in Visual Basic

通过 My.Computer.FileSystem 对象的 DeleteFile 方法,可以删除文件。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

  • 使用 DeleteFile 方法删除文件。Use the DeleteFile method to delete the file. 以下代码演示如何删除名为 test.txt 的文件。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

  • 使用 DeleteFile 方法删除文件,同时将 showUI 设置为 AllDialogsUse the DeleteFile method to delete the file, setting showUI to AllDialogs. 以下代码演示如何删除名为 test.txt 的文件,并允许用户确认是否应删除该文件。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

  • 使用 DeleteFile 方法删除文件,并为 recycle 参数指定 SendToRecycleBinUse the DeleteFile method to delete the file, specifying SendToRecycleBin for the recycle parameter. 以下代码演示如何删除名为 test.txt 的文件并将其发送到“回收站” 。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