【问题标题】:Absent .txt file causes my program to crash缺少 .txt 文件会导致我的程序崩溃
【发布时间】:2010-08-13 09:22:24
【问题描述】:

我正在使用 VB6。在 Form.Load 中,我使 C:\test.txt 中的文本填充 Text1.text。我的问题是如果文件 C:\test.txt 不存在,我的程序就会出错。这是我正在使用的代码:

nFileNum = FreeFile

Open "C:\test.txt" For Input As nFileNum
lLineCount = 1

    Do While Not EOF(nFileNum)
       Line Input #nFileNum, sNextLine
       sNextLine = sNextLine
       sText = sText & sNextLine
    Loop

Text1.Text = sText
Close nFileNum

如果文件丢失,我怎样才能得到一个 MsgBox 或其他通知,而不是程序崩溃? (这样我就可以继续使用该程序,但只是被通知该文件不存在)

【问题讨论】:

  • 这是 VB6 还是 VB.NET?请清除,它混淆了海报
  • @Darknight,是VB6,再看问题...
  • 我明白,但为什么是 .NET 标签?因此,一些用户已经/将发布 VB.NET 解决方案。
  • 对不起.NET标签,它是VB6。

标签: vb6 text


【解决方案1】:

您需要在代码中添加错误处理。然后检查错误信息或错误代码,然后决定是否显示警告信息。

On Error GoTo err_check
nFileNum = FreeFile 

Open "C:\test.txt" For Input As nFileNum 
lLineCount = 1 

    Do While Not EOF(nFileNum) 
       Line Input #nFileNum, sNextLine 
       sNextLine = sNextLine 
       sText = sText & sNextLine 
    Loop 

Text1.Text = sText 
Close nFileNum

Exit Sub

err_check:
'Check error code/message and display warning message box here

【讨论】:

  • 我不想那样做...我想具体知道该文本文件是否存在。
  • 抱歉没有看到你的代码,我试试看,如果可行的话我觉得不错。
  • 要检查文件是否存在,请使用 FSO 对象(您需要在项目中添加对 dll 的引用) Set oFSO = CreateObject("Scripting.FileSystemObject") ' 检查文件并返回适当的结果If oFSO.FileExists('C:\test.txt') Then 'exists Else '不存在 End if
  • 谢谢,我试过了,它有效,它给了我很多选择去做其他事情。太好了,再次感谢您。
  • 首先,这段代码总是会碰到 err_check 代码,所以它应该在 err_check-label 之前退出 sub。其次,当错误被捕获时,您可以检查 Err.Number 中的错误代码。根据此处的错误代码列表(support.microsoft.com/kb/142138/EN-US),Err.Number = 53。
【解决方案2】:

试试

nFileNum = FreeFile

Open "C:\test.txt" For Input As nFileNum

If (nFileNum Is Nothing) Then
    MsgBox "Hello there!"
Else
    lLineCount = 1

        Do While Not EOF(nFileNum)
           Line Input #nFileNum, sNextLine
           sNextLine = sNextLine
           sText = sText & sNextLine
        Loop

    Text1.Text = sText
    Close nFileNum
End If

【讨论】:

  • 我知道你的问题已经解决了,但是对于未来,如果你指定你得到的错误而不是仅仅说你得到一个错误会有所帮助;)
  • 其实我的问题又回来了。无论文件是否存在,我得到的代码都会出现错误 msgbox。没有具体的错误,只是说运行时无效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 2011-12-08
  • 2021-12-27
相关资源
最近更新 更多