How to read contents from a file, do some processing, then write to a text box - vb.net

It's been nearly 20 years since I last used VB.NET and I've forgotten everything :( My project:
Read the contents of a text file and write to a text box
If the line contains a specified string, write to a second text box
Repeat until end of file
What I have so far:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.SourceText.LoadFile("e:\xdcc.txt", RichTextBoxStreamType.PlainText)
Dim Term As String = "Santa"
For Each Line As String In IO.File.ReadLines("e:\xdcc.txt")
If Line.Contains(Term) = True Then
OutputText.Text = (Line) & vbNewLine
End If
Exit For
Next
End Sub
Problem:
I can read the contents to the first text box and I can output a matching line to the second text box. It's not parsing the rest of the file and writing all the subsequent matches.
Thank you

I believe there are two mistakes here:
first, your Exit For statement is causing the For loop to end on the first iteration;
Second, as I understood in your question you want to show in the text box all of the matches found inside the file. You need to concatenate the 'Current text' with the next match.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.SourceText.LoadFile("e:\xdcc.txt", RichTextBoxStreamType.PlainText)
Dim Term As String = "Santa"
For Each Line As String In IO.File.ReadLines("e:\xdcc.txt")
If Line.Contains(Term) = True Then
'OutputText.Text = (Line) & vbNewLine
OutputText.Text &= (Line) & vbNewLine
End If
'Exit For
Next
End Sub
That might solve your problem.

Remove the Exit For. that is causing the loop to end after the first round about

Think I figured it out. I removed that Exit For statement and in the If section I changed it to:
OutputText.Text = OutputText.Text & (Line) & vbNewLine
I now get the results that I was looking for

Related

VB.NET how to save listview with savefiledialog

Something's wrong in my code, i want to save listview item into text file using savefiledialog.
I'm getting error "Overload resolution failed because no accessible 'WriteAllLines' accepts this number of arguments."
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles ChromeButton3.Click
Dim s As New SaveFileDialog
s.Filter = "text|*.txt"
s.Title = "Save Your Hits"
If s.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each myItem As ListViewItem In ListView1.Items
File.WriteAllLines(myItem.Text & vbNewLine & myItem.SubItems(1).Text & vbNewLine & myItem.SubItems(2).Text & vbNewLine & myItem.SubItems(3).Text & vbNewLine & vbNewLine)
Next
End If
End Sub
Your error
Overload resolution failed
can be corrected by looking at the documentation. It is a good idea to do this with any unfamiliar method. Just google the method followed by "in .net" The first link that came up is https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netframework-4.8
And the first topic in the documentation is overloads. I think you can see that none of the overloads match what you tried to pass.
As was mentioned in comments File.Write All lines isn't really appropriate for your purposes. Instead of making all those lines and a double line between records, Make each row a single line separating each field by a comma. I used a StringBuilder which provides a mutable (changeable) datatype (unlike a String which is immutable). Saves the compiler from throwing away and creating new strings on every iteration.
I appended a new line on each iteration containing an interpolated string. An interpolated string starts with the $. This allows you to directly mix in variables enclosed in { } with the literal characters.
After the loop, you convert the StringBuilder to a String and write to the file with the file name provided by the dialog box.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim s As New SaveFileDialog
s.Filter = "text|*.txt"
s.Title = "Save Your Hits"
If s.ShowDialog = DialogResult.OK Then
Dim fileName = s.FileName
Dim sb As New StringBuilder
For Each myItem As ListViewItem In ListView1.Items
sb.AppendLine($"{myItem.Text},{myItem.SubItems(1).Text},{myItem.SubItems(2).Text},{myItem.SubItems(3).Text}")
Next
File.WriteAllText(fileName, sb.ToString)
End If
End Sub

Not read text file correct

I want when I read txt file and add in ListBox1.items, add this text http://prntscr.com/on12e0 correct text §eUltra §8[§716x§8].zip not like this http://prntscr.com/on11kv
My code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
My.Computer.FileSystem.CopyFile(
appDataFolder & "\.minecraft\logs\latest.log",
appDataFolder & "\.minecraft\logs\latestc.log")
Using reader As New StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\logs\latestc.log")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(" Reloading ResourceManager: Default,") Then
Dim lastpart As String = line.Substring(line.LastIndexOf(", ") + 1)
ListBox1.Items.Add(lastpart)
End If
End While
End Using
My.Computer.FileSystem.DeleteFile(appDataFolder & "\.minecraft\logs\latestc.log")
End Sub
This question is only different from your first question in that your have substituted a ListBox for a RichTextBox. It seems you got perfectly acceptable answers to your first question. But I will try again.
First get the path to the file. I don't know why you are copying the file so I didn't.
Add Imports System.IO to the top of your file. The you can use the File class methods. File.ReadAllLines returns an array of strings.
Next use Linq to get the items you want. Don't update the user interface on each iteration of a loop. The invisible Linq loop just adds the items to an array. Then you can update the UI once with .AddRange.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim appDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\.minecraft\logs\latest.log")
Dim lines = File.ReadAllLines(appDataFolder)
Dim lstItems = (From l In lines
Where l.Contains(" Reloading ResourceManager: Default,")
Select l.Substring(l.LastIndexOf(", ") + 1)).ToArray
ListBox1.Items.AddRange(lstItems)
End Sub
If this answer and the previous 2 answer you got don't work, please lets us know why.

Equals Not Working VB.Net

I am trying to compare two strings that I know are equal to each other, but it is always skipping to the else. I've tried everything, .Equals, =, IsNot, they all don't work! The frustrating part is that I know the strings are equal! Please take a look at my code and see if it there is possible anything wrong with it.
Public Class Form1
Dim log As String
WithEvents xworker As New System.ComponentModel.BackgroundWorker
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
xworker.RunWorkerAsync()
End Sub
Private Sub xWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles xworker.DoWork
Dim qWorker = CType(sender, System.ComponentModel.BackgroundWorker)
Dim client As New Net.WebClient
log = client.DownloadString("http://########/log.txt")
End Sub
Private Sub xWorker_Completed(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles xworker.RunWorkerCompleted
If log.Equals(RichTextBox1.Text) Then
xworker.RunWorkerAsync()
Else
RichTextBox1.Text = log
xworker.RunWorkerAsync()
End If
End Sub
End Class
You needed to listen to #SLaks and #Hans Passant, they were right on the money.
I setup your code sample and it worked correctly if the source log.txt file didn't have a line terminator in it. Once I added the line terminator I got the results your are getting.
From the command window:
>? RichTextBox1.Text.Length
14
>? log.length
15
Using the QuickWatch window, and TABing until the Value field was selected:
Log result:
"log test 1234" & vbCrLf & ""
RichTextBox result:
"log test 1234" & vbLf & ""
The fix to the problem depends on what will actually get written to the log.txt file. I assume that "log test 1234" is just development code. If you are only interested in a single line as a result code then make sure you are not writing a line terminator. If your result codes are more complicated then you will need to do more parsing on the result than just an Equals compare.
Try this instead.
If log.ToLower().Trim() = RichTextBox1.Text.ToLower().Trim() Then
I think this is case sensitve compare. You should convert both of the strings to upper or to lower and then compare them
If Log.ToLower() = RichTextBox1.Text.ToLower() Then
Or you can use String.Compare method and set third param to true to ignore case
If String.Compare(log, RichTextBox1.Text, True) = 0 Then
I've read that the RichTextBox can change line endings when Text gets set. So the Text property might be returning a string that is different than what was set. I haven't been able to verify, but you can probably devise a quick test of this theory.

creating text file in VB.NET adding extra line

I am trying to create text file with the code below; but there is always an extra line at the end that I cannot get rid of. Is there any way to modify this code to write the text file without the last line?? Help appreciated:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MekdamFile As String
MekdamFile = "C:\TEMP\MEKDAM.txt"
Dim dones As New List(Of String)
For i = 1 To 10
dones.Add("test test " & i)
Next
Using sw As New StreamWriter(MekdamFile)
For Each i As String In dones
sw.WriteLine(i)
Next
End Using
End Sub
End Class
Thanks for help in advance...
StreamWriter.WriteLine always writes a line terminator.
On the last iteration of the loop you could use sw.Write instead.
Your code can be simplified a bit:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
File.WriteAllText("C:\TEMP\MEKDAM.txt", [String].Join( _
Environment.NewLine, _
Enumerable.Range(1, 10).[Select](Function(i) "Test test" + Cstr(i))))
End Sub
You are calling WriteLINE, so whatever you pass into it will be appended with a newline character sequence.
If you don't want to write the newline, use Write instead of WriteLine. Of course, you should then append the newline yourself for all lines except the last.
Alternatively, for a small text, just build the whole text, then trim the end of it and write it at once:
Dim sb As new StringBuilder();
For i = 1 To 10
sb.AppendLine("line " + i);
Next
File.WriteAllText(path, sb.ToString().TrimEnd());

Only get characters surrounded by " "

I'm Currently writing a program that will convert my code into Pseudo Code but I'm having the problem that I cannot figure out how to get Only text that is surrounded by " " and comes after the word print.
Currently have
Dim str() As String = TextBox1.Text.Split()
If str.Contains("Print") Then
End If
Nothing
Here is one way. Instead of splitting and then checking for Print, Check for Print first and then split it.
Tried and Tested
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If TextBox1.Text.Contains("Print") Then
Dim ar As String = TextBox1.Text.Substring(TextBox1.Text.IndexOf("Print"))
Dim splitted() As String = Split(ar, """")
If splitted.Length > 1 Then MessageBox.Show(splitted(1))
End If
End Sub
If the string is say This "is" a great Print Job! "Nice Work" then the above code should give you Nice Work