删除指定的路径文件,如果没有文件,则显示 msgbox



我想通过询问MsgBoxStyle.YesNo来删除指定目录中的文件,如果这些文件不存在,则显示msgbox。

我尝试了以下代码,但只有MsgBoxStyle.YesNo打开,没有其他反应。

    Dim di As IO.DirectoryInfo = New IO.DirectoryInfo(Application.StartupPath & "....1.txt")
    Dim di1 As IO.DirectoryInfo = New IO.DirectoryInfo(Application.StartupPath & "....2.txt")
    Dim di2 As IO.DirectoryInfo = New IO.DirectoryInfo(Application.StartupPath & "....3.txt")
    If MsgBox("Are you sure?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
    ElseIf di.Exists And di1.Exists And di2.Exists Then
        My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....1.txt")
        My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....2.txt")
        My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....3.txt")
        MsgBox("Done!", MsgBoxStyle.Exclamation)
    Else
        MsgBox("No file found!", MsgBoxStyle.Exclamation)
    End If

我还尝试了以下代码。但这次如果文件不存在,应用程序就会崩溃。

Dim di As IO.DirectoryInfo = New IO.DirectoryInfo(Application.StartupPath & "....1.txt")
Dim di1 As IO.DirectoryInfo = New IO.DirectoryInfo(Application.StartupPath & "....2.txt")
Dim di2 As IO.DirectoryInfo = New IO.DirectoryInfo(Application.StartupPath & "....3.txt")
If di.Exists And di1.Exists And di2.Exists Then
ElseIf MsgBox("Are you sure?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
    My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....1.txt")
    My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....2.txt")
    My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....3.txt")
    MsgBox("Done!", MsgBoxStyle.Exclamation)
Else
    MsgBox("No file found!", MsgBoxStyle.Exclamation)
End If

我做错了什么?

这两种解决方案中,您都错误地使用了'ElseIf'.corrct 方法来做到这一点:

  1. 解决方案 1:

    If MsgBox("Are you sure?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
        If di.Exists And di1.Exists And di2.Exists Then
            My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....1.txt")
            My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....2.txt")
            My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....3.txt")
            MsgBox("Done!", MsgBoxStyle.Exclamation)
        Else
            MsgBox("No file found!", MsgBoxStyle.Exclamation)
        End If
    End If
    
  2. 解决方案 2:

      If di.Exists And di1.Exists And di2.Exists Then
        If MsgBox("Are you sure?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....1.txt")
            My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....2.txt")
            My.Computer.FileSystem.DeleteFile(Application.StartupPath & "....3.txt")
            MsgBox("Done!", MsgBoxStyle.Exclamation)
        Else
            MsgBox("No file found!", MsgBoxStyle.Exclamation)
    End If
    

相关内容

最新更新