检查文件是否存在,然后重试

时间:2013-05-23 18:35:46

标签: vb.net winforms file-io messagebox dialogresult

我有一个检查文件存在的函数(return file.exists(file))。 如果它不存在,那么我显示一个错误消息,其中包含Abort,Retry,Ignore选项。

我的麻烦是我无法重试。

我试过把代码放在检查文件是否存在于单独的函数中,然后从select case语句的重试案例中调用该函数,但它似乎已经过去(因为它已经知道它没有&# 39; t存在?)我尝试创建一个单独的类,其中包含检查文件是否存在的函数,然后每次调用它时创建该类的新实例,但这没有帮助。

我错过了什么吗?

我希望每次用户点击重试时应用程序都会再次检查,直到他们按下中止或忽略(或者当然它确实找到了文件。

处理重试的正确方法是什么?

Private Sub main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    If CheckFileExists() Then
     'do stuff here
    End If
End Sub

Private Function CheckFileExists()
    If Not FindFile() Then
        Select Case MessageBox.Show("Can't Find File", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
            Case Windows.Forms.DialogResult.Abort
                End
            Case Windows.Forms.DialogResult.Retry
                Return FindFile()
            Case Windows.Forms.DialogResult.Ignore
                MessageBox.Show("Proceeding without file present")
                'do some other stuff
                Return True
            Case Else
                Return False
        End Select
    Else
        Return True
    End If
End Function

Private Function FindFile() As Boolean
    Return System.IO.File.Exist(path\file.ext)
End Function

我也试过把它放到课堂上:

Private Function FindFile() As Boolean
    Dim fc As New FileCheck
    If Not fc.fnFileCheck() Then
        Return False
    Else
        Return True
    End If
End Function


Public Class FileCheck
Public Function fnFileCheck() As Boolean
    Return System.IO.File.Exist(path\file.ext)
End Function
End Class

1 个答案:

答案 0 :(得分:1)

如果您想继续检查文件,直到按下中止或忽略,我认为您必须在“重试”案例中拨打CheckFileExists()而不是FindFile()

Private Function CheckFileExists()
    If Not FindFile() Then
        Select Case MessageBox.Show("Can't Find File", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error)
            Case Windows.Forms.DialogResult.Abort
                End
            Case Windows.Forms.DialogResult.Retry
                Return CheckFileExists()
            Case Windows.Forms.DialogResult.Ignore
                MessageBox.Show("Proceeding without file present")
                'do some other stuff
                Return True
            Case Else
                Return False
        End Select
    Else
        Return True
    End If
End Function
相关问题