tags:

views:

56

answers:

2

Im using VB6. In Form.Load I make the text found in C:\test.txt fill Text1.text. My problem is if the file C:\test.txt doesn't exist, my program just errors. How can I make it so that I get a MsgBox or other notification if the file is missing, instead of a program crash? (So that I can continue on with the program, but just be notified that the file isn't there) Here's the code I'm using:

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
A: 

Try

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
Tchami
Still gave me an error.
Exist
I see you got your problem fixed, but for the future it'd help if you specified the error you get instead of just saying you get an error ;)
Tchami
Actually, my problem's back. The code that I got made the error msgbox come up regardless if the file's there or not. There is no specific error, it just says invalid runtime.
Exist
+1  A: 

You need to add Error Handling to your code. Then check for the error message or error code, and then decide to display a warning message or not.

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
J Angwenyi
I don't want to do that... I want to know specifically if that text file exists or not.
Exist
Sorry didn't see your code, I will try it, looks good to me if it works.
Exist
To check if file Exists, Use FSO object (you need to add a reference to the dll to your project) Set oFSO = CreateObject("Scripting.FileSystemObject")' Check for file and return appropriate resultIf oFSO.FileExists('C:\test.txt') Then'existsElse'does not existEnd if
J Angwenyi
Thanks, I tried it out, it works and it gives me a lot of options to do other stuff. Just great, thank you again.
Exist
Firstly, this code will always run into the err_check code, so it should exit sub before the err_check-label. Secondly, you can check the error code in Err.Number when the error has been trapped. According to the list of error codes here (http://support.microsoft.com/kb/142138/EN-US/), Err.Number = 53.
gamen
Where do I put the err_check code then?
Exist
Just before err_check: add a line of code Exit Sub
J Angwenyi