【问题标题】:Check if File exists, then Retry检查文件是否存在,然后重试
【发布时间】:2013-05-19 06:08:26
【问题描述】:

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

我的问题是我无法让它重试。

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

我错过了什么吗?

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

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

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 谢谢安德里亚。我确定我试过了,但也许我没有将它与我必须改变的其他东西结合起来尝试。当我使用该类的新实例来检查并调用 CheckFileExists 而不是 FindFiles 时,它可以工作。我确信必须有一种更清洁的方法来做到这一点,但这很有效!谢谢。
    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2017-10-01
    • 2017-04-27
    相关资源
    最近更新 更多