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
Related
Please help me how to list all records meets criteria in text box (line by line) as the below code retrieve the first record only .
Note : i tried to enable multi lines in text box but an error appeared"Can't assign to read only property"
Any help please with amending the beloe code
Dim iFile As Integer
Dim sLine As String, sNewText As String
iFile = FreeFile
Open App.Path & "\text1.txt" For Input As #iFile
Do While Not EOF(iFile)
Line Input #iFile, sLine
If sLine Like "*TOTAL INTERCHANGE*" Then
Text5.Text = sLine
End If
Loop
Close
To find out if your line is containing the string "TOTAL INTERCHANGE" You can also use Instr (don't worries, Like works also just fine).
If Instr(1, sLine, "TOTAL INTERCHANGE") > 0 Then
Text5.Text = Text5.Text & sLine & vbCrLf
End If
Here is the reference and you can also quickly test it online:: VBScript InStr Function (it is VBScript, not VB6 but it doesn't matter, it is identical)
Regarding the MultiLine property, you should set it in the VB6 IDE, not by code.
To the point:
please note that you shouldn't replace the whole content of the TextBox but appending the new lines at the end by keeping the actual content of the TextBox and just inserting a line break. This is what the Text5.Text = Text5.Text & sLine & vbCrLf does.
Can you also post what's inside the text1.txt file? Also do you really need to check the sLine for something like TOTAL INTERCHANGE value? By the way you are just overwriting the value of text5.text everytime. It should be
Text5.Text = Text5.Text & sLine
OR
Text5.Text = Text5.Text & sLine & vbCrLf
Also, you should be able to set the MultiLine to true at design time with no problem.
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.
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.
I Have Displayed text file in richtextbox.
and onclick on command button value of textbox1 is being replaced in text file.
but How to keep both data . previous one and another which is entered new in textbox
I HAVE USE THIS CODE BUT IT REPLACES ALL THE TEXT :
Open "D:\chat.txt" For Output As #1
a = Text1.Text
Print #1, a
Close #1
Change For Output to For Append, and it will add the new text to the end of the file instead of overwriting it.
Additional note
Since I'm not able to add a comment to Boann's answer (the one marked as accepted).
The Append access mode used with the Print statement automatically appends a new line at the end of the file. This is fine in almost all cases, but for anyone reading this that wants to avoid this behavior, just add a semicolon at the end of the Print statement (this is the only instance I've seen the semicolon used in VB6).
a = Text1.Text
intHandle = FreeFile
Open "D:\chat.txt" For Append As intHandle
Print #intHandle, a; ' Notice the semicolon; prevents a new line after this output.
Close #intHandle
I'm sure the code you posted originally was just for the sake of getting an answer and is not what your code actually looks like. Otherwise:
To you or any future readers, here's a simple AppendToFile() function which will make repeated calls easier, ensures the file gets closed even if a run-time error is encountered, and shows useful debug information upon failure (i.e. with an invalid filename):
How your original code would be written when putting my below function in your code:
AppendToFile "D:\chat.txt", Text1.Text
And here's the function:
Private Function AppendToFile( _
ByRef FilePath As String, _
ByRef Text As String, _
Optional ByVal AppendNewLine As Boolean = True _
) As Boolean
On Error GoTo ErrorHandler
Dim intHandle As Integer
' Get an available file handle to use.
intHandle = FreeFile
Open FilePath For Append As intHandle
' Only use semicolon at end if we do NOT want to append a new line.
If AppendNewLine Then
Print intHandle, Text
Else
Print intHandle, Text;
End If
Close intHandle
intHandle = 0
AppendToFile = True
Exit Function
ErrorHandler:
' Ensure that file is indeed closed.
If intHandle <> 0 Then
Close intHandle
End If
' Show error in debug window (CTRL+G)
Debug.Print _
"Error (#" & CStr(Err.Number) & ") in " & _
"TextToFile( _" & vbCrLf & _
"`" & FilePath & "`, _" & vbCrLf & _
"`" & Text & "`, _" & vbCrLf & _
IIf(AppendNewLine, "`True`", "`False`") & vbCrLf & _
"): " & Err.Description & IIf("." = Right$(Err.Description, 1), "", ".") & vbCrLf
Exit Function
End Function
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