Absent .txt file causes my program to crash - vb6

I'm 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. 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
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)

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

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

Related

Error 800A03EE in my VB script while running through command prompt

I am running through command prompt on Windows and I am getting the alert at 24th line and 34th char
Code sample are as follows:
Sub CatchMe()
Dim outobj, mailobj
Dim strFileText
Dim objFileToRead
Set outobj = CreateObject("Outlook.Application")
Set mailobj = outobj.CreateItem(0)
strFileText = GetText("C:\Users\Yatheesh.Sathyanaray.STDC\Documents1.txt")
With mailobj
.To = "yatheesh.satyanarayana#stratogent.com"
.Subject = "Testmail"
.Body = strFileText
.Display
End With
'Clear the memory
Set outobj = Nothing
Set mailobj = Nothing
End Sub
Function GetText(sFile As String) As String
Dim nSourceFile As Integer, sText As String
nSourceFile = FreeFile
'Write the entire file to sText
Open sFile For Input As #nSourceFile
sText = Input$(LOF(1), 1)
Close
GetText = sText
End Function
It works in my machine with your code provide. I've tested it in a Excel file and copy your code as below:
However, I'm noticed you used a property named "FreeFile", Use without what it seems that.

How to read a specific line in txt file vb 6

I would like to read a specific line in a .txt file in a vb 6.0 program. My intrest is where a particular line where a certain text appears. I am trying to apply this code which I got from another project.
Dim strLine As String
Open "E:\Projects\VB\Ubunifu\MyList.txt" For Input As #1
Line Input #1, strLine ' read one line at a time vs entire file
lblCurrent.Caption = strLine
Line Input #1, strLine
lblO.Caption = strLine
Close #1
however this doesnt seem to be working it says "input past end of file"
You can try this:
Private Sub Form_Load()
Text1.MultiLine = True
Open "E:\Projects\VB\Ubunifu\MyList.txt" For Input As #1
Text1.Text = Input$(LOF(1), #1)
lblCurrent.Caption = udf_ReadLine(Text1.Text, 1) ' read line #1
lblCurrent_i.Caption = udf_ReadLine(Text1.Text, 2) ' read line #2
Close #1
End Sub
Private Function udf_ReadLine(ByVal sDataText As String, ByVal nLineNum As Long) As String
Dim sText As String, nI As Long, nJ As Long, sTemp As String
On Error GoTo ErrHandler
sText = ""
nI = 1
nJ = 1
sTemp = ""
While (nI <= Len(sDataText))
Select Case Mid(sDataText, nI, 1)
Case vbCr
If (nJ = nLineNum) Then
sText = sTemp
End If
Case vbLf
nJ = nJ + 1
sTemp = ""
Case Else
sTemp = sTemp & Mid(sDataText, nI, 1)
End Select
nI = nI + 1
Wend
If (nJ = nLineNum) Then
sText = sTemp
End If
udf_ReadLine = sText
Exit Function
ErrHandler:
udf_ReadLine = ""
End Function
I just added a function to read line from a string, and you can keep using the LOF function as you wish, also all of the concept from your original code.
First, if you had searched for your error you would have found the cause, https://msdn.microsoft.com/en-us/library/aa232640(v=vs.60).aspx.
Second, you need to do something to ensure there is anything in the file to read. https://msdn.microsoft.com/en-us/library/aa262732(v=vs.60).aspx
Finally, use a loop to read lines from the file. It appears you want the first line displayed in one label and the second line displayed in another. The code below reads one line at a time from the file, decides if it is reading an odd line number (first line) or even line number (second line) and displays the line in the label. After each line is read it looks for "a certain text" whatever that may be, and if found it exits the loop and closes the file.
Open "E:\Projects\VB\Ubunifu\MyList.txt" For Input As #1
Do While EOF(1) = False
Line Input #1, strLine ' read one line at a time vs entire file
lngLineNum = lngLineNum + 1 'Am I reading an odd or even line number
If lngLineNum Mod 2 <> 0 Then
lblCurrent.Caption = strLine
Else
lblO.Caption = strLine
End If
If InStr(1, strLine, "a cetain text", vbTextCompare) > 0 Then
Exit Do
End If
Loop
Close #1
Note that I did not check that strLine contained anything before calling InStr. If it is empty the InStr function will cause an error. You should add some defensive coding. At the very least an error handler.

Output XMLHttp response line by line

I need to grab a log file from a URL and then print the log file line by line. I can successfully get the file this way:
Dim filePath,fileName
filePath = "http://localhost/osat/spawn_pi_logs"
fileName = "/Spawn.log"
FilePath = filePath & fileName
Set req = CreateObject("Msxml2.XMLHttp.6.0")
req.open "GET", FilePath, False
req.send
If req.Status = 200 Then
Response.Write "Found the file<br>"
Response.Write req.responsetext
End If
That code writes the text of my log file to the screen in one huge ugly blob. I want to walk through it, format it, search it, etc and write it out with code similar to this:
Do While Not TextStream.AtEndOfStream
Dim sLine
sLine = TextStream.readLine
sLine = sLine & "<br>"
Response.Write sLine
Loop
However, how do I convert my req object (which has a generic stream at req.ResponseStream) and convert it to a Text Stream?
You can save the response to a text file by incorporating an ADO Stream and writing the responseBody:
If req.Status = 200 Then
With CreateObject("ADODB.Stream")
.Type = 1 'adTypeBinary
.Open
.Write req.responseBody
.SaveToFile "c:\myfile.txt"
.Close
End With
End If
Then you can open your text file using OpenTextFile() and read it as a TextStream.
But, you could just split your responseText into an array with the Split() function and not worry about saving and reading a text file:
If req.Status = 200 Then
' Create a line array...
a = Split(req.responseText, vbCrLf)
For i = 0 To UBound(a)
' Process each line
Next
End If
Thank you PHD443322. This code works great:
a = Split(req.responsetext, vbCrLf)
for each x in a
response.write(x & "<br />")
next
The key was not only the Split command, but also using the VBScript vbCrLf constant to set the delimiter.

VB 6 + Capture text from file and copy it to form window

The following VB 6 code saves text from the textBox in the form GUI to file.txt (By the click on the button)
How to do the reverse option – copy/capture file text (file.txt) , and passed it on the textBox in the form GUI , I will happy to get real example
remark - (before passed need to clear the form window from any text )
Private Sub save_Click()
saves = (Form1.Caption)
FCO.CreateTextFile App.Path & "\" & saveas & "file.txt", True
FCO.OpenTextFile(App.Path & "\" & saveas & "file.txt", ForWriting).Write Text1.Text
End Sub
This reads from a file and puts the results in Text1.Text.
Private Sub save_Click()
Dim sFile as String
sFile = "c:\whatever"
Dim sData as String
Dim fnum as Integer
fnum = FreeFile()
Open sFile For Input As #fnum
If Not eof(fnum) Then
Input #fnum, sData
Text1.Text= sData
End If
Close #fnum
End Sub
You can load in the contents of a file using the standard VB6 file I/O operations
Dim FileNum As Integer
Dim Size As Long
Dim Data() As Byte
'Open the file
FileNum = FreeFile()
Open FileName For Binary As #FileNum
'Read all the data
Size = LOF(FileNum)
ReDim Data(Size - 1)
Get #FileNum, , Data
Close #FileNum
'Convert to a string
TextBox.Text = StrConv(Data, vbUnicode)
See the original article.

VB6 not desired result reading c:\test.txt

I start out with text103.text having a text value of what I want to check C:\test.txt for. So if whatever's in text103.text matches up with whatever's in C:\test.txt label3.caption should read "success" yet every time I run it, I get "failure" why??
So here's the code in my button:
Private Sub Command1_Click()
nFileNum = FreeFile
Open "C:\test.txt" For Input As nFileNum
lLineCount = 1
Do While Not EOF(nFileNum)
Line Input #nFileNum, sNextLine
sNextLine = sNextLine & vbCrLf
sText = sText & sNextLine
Loop
Text102.Text = sText
Close nFileNum
If Text102.Text = Text103.Text Then
Label3.Caption = "success"
Else
Label3.Caption = "failure"
End If
End Sub
Even when my text103.text starts out as "hello" and I edit the C:\test.txt to just say "hello" it always gives me label3.caption "failure"!!! Why???
Possibly because you are always adding a newline to the data read from the file.
Does Text103.Text contain a new line too?
Update:
vbCrLf aka \r\n are part of the set of whitespace characters so you may not be able to see them directly.
Before If Text102.Text = Text103.Text Then try
msgbox "Len 102 " & Len(Text102.Text) & " Len 103 " & Len(Text103.Text)
this will show that the strings are different lengths, therefore they cannot be equal.
Alternatively, in immediate mode try ? "[" & text102.Text & "]" and ? "[" & text103.Text & "]" Assuming the word in question is "Hello", I'll bet the first will print
[Hello
]
and the second
[Hello]
It's because you are adding newline characters text103.text does not have this.
Could it be to do with your trailing carriage return? It looks like your file read will always have a vbCrLf on the end of it whereas possibly your text103 doesn't. Can you go into debug mode and confirm exactly what each string contains?
I'd make a guess that it's to do with the newlines (vbCrLf) that you add, or some similar character.
Otherwise it might be case dependant, you could try adding Option Compare Text at the top of the file.
Try this:
Private Sub Command1_Click()
nFileNum = FreeFile
Open "C:\test.txt" For Input As nFileNum
lLineCount = 1
Do While Not EOF(nFileNum)
Line Input #nFileNum, sNextLine
sNextLine = sNextLine & vbCrLf
sText = sText & sNextLine
Loop
Text102.Text = sText
Close nFileNum
If Replace$(Text102.Text, VBCrLf, "") = Replace$(Text103.Text, VbCrLf, "") Then
Label3.Caption = "success"
Else
Label3.Caption = "failure"
End If
End Sub

Resources