Changing result from line 2 to line 1 - vb.net

I have a vb.net application that is made to acquire a result from a webpage to my alertbox.
The webpage's result however is on the second line and is spaced.
I can only see half the text which is inside the alertbox since it's on line 2.
How do i change it so that the result goes to line 1?
The webpage result is like this:
1
2 Success: 127.0.0.1 works
However I want it to show up on my alertbox like this:
1 Success: 127.0.0.1 works
I've fixed the spacing so far, but I can't fix the lines.
Here's the code:
Dim Website2 As New WebClient
Dim WebsiteIW As String = Website2.DownloadString("http://webpage.com/" + FlatTextBox1.Text)
If WebsiteIW.Length > 37 Then WebsiteIW = WebsiteIW.Substring(0, 37)
While WebsiteIW.Contains(" ")
WebsiteIW = WebsiteIW.Replace(" ", "")
End While
FlatAlertBox1.Text = WebsiteIW

Instead of
While WebsiteIW.Contains(" ")
WebsiteIW = WebsiteIW.Replace(" ", "")
End While
Use
WebsiteIW = WebsiteIW.trim
It's a lot faster, and will get rid of an stray newline characters.

Related

Fastest Method to (read, remove, write) to a Text File

I coded a simple program that reads from a Textfile Line by Line and If the current readed Line has alphabetics (a-z A-Z) it will write that Line into an other txt file.
If the current readed line doesn't have alphabetics it wont write that line into a new text file.
I created this for the purpose that I have members registering at my website and some of them are using only numbers as Username. I will filter them out and only save the alphabetic Names. (Focus on this Project please I know i could just use php stuff)
That works great already but it takes a while to read line by line and write into the other text file (Write speed 150kb in 1 Minute - Its not my drive I have a fast ssd).
So I wonder if there is a faster way. I could "readalllines" first but on large files it just freezes my program so I don't know if that works too (I want to focus on large +1gb files)
This is my code so far:
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
Dim myFile As New FileInfo(output)
Dim sizeInBytes As Long = myFile.Length
If sizeInBytes > splitvalue Then
outcount += 1
output = outputold + outcount.ToString + ".txt"
File.Create(output).Dispose()
End If
count += 1
TextLine = objReader.ReadLine() & vbNewLine
Console.WriteLine(TextLine)
If CheckForAlphaCharacters(TextLine) Then
File.AppendAllText(output, TextLine)
Else
found += 1
Label2.Text = "Removed: " + found.ToString
TextBox1.Text = TextLine
End If
Label1.Text = "Checked: " + count.ToString
Loop
MessageBox.Show("Finish!")
End If
First of all, as hinted by #Sean Skelly updating UI controls - repeatedly - is an expensive operation.
But your bigger problem is File.AppendAllText:
If CheckForAlphaCharacters(TextLine) Then
File.AppendAllText(output, TextLine)
Else
found += 1
Label2.Text = "Removed: " + found.ToString
TextBox1.Text = TextLine
End If
AppendAllText(String, String)
Opens a file, appends the specified string to the file, and then
closes the file. If the file does not exist, this method creates a
file, writes the specified string to the file, then closes the file.
Source
You are repeatedly opening and closing a file, causing overhead. AppendAllText is a convenience method since it performs several operations in one single call but you can now see why it's not performing well in a big loop.
The fix is easy. Open the file once when you start your loop and close it at the end. Make sure that you always close the file properly even when an exception occurs. For that, you can either invoke the Close in a Finally block, or use a context manager, that is keep your file write operations within a Using block.
And you could remove the print to console as well. Display management has a cost too. Or you could print status updates every 10K lines or so.
When you've done all that, you should notice improved performance.
My Final Code - It works a lot faster now (500mbs in 1 minute)
Using sw As StreamWriter = File.CreateText(output)
For Each oneLine As String In File.ReadLines(FILE_NAME)
Try
If changeme = True Then
changeme = False
GoTo Again2
End If
If oneLine.Contains(":") Then
Dim TestString = oneLine.Substring(0, oneLine.IndexOf(":")).Trim()
Dim TestString2 = oneLine.Substring(oneLine.IndexOf(":")).Trim()
If CheckForAlphaCharacters(TestString) = False And CheckForAlphaCharacters(TestString2) = False Then
sw.WriteLine(oneLine)
Else
found += 1
End If
ElseIf oneLine.Contains(";") Or oneLine.Contains("|") Or oneLine.Contains(" ") Then
Dim oneLineReplac As String = oneLine.Replace(" ", ":")
Dim oneLineReplace As String = oneLineReplac.Replace("|", ":")
Dim oneLineReplaced As String = oneLineReplace.Replace(";", ":")
If oneLineReplaced.Contains(":") Then
Dim TestString3 = oneLineReplaced.Substring(0, oneLineReplaced.IndexOf(":")).Trim()
Dim TestString4 = oneLineReplaced.Substring(oneLineReplaced.IndexOf(":")).Trim()
If CheckForAlphaCharacters(TestString3) = False And CheckForAlphaCharacters(TestString4) = False Then
sw.WriteLine(oneLineReplaced)
Else
found += 1
End If
Else
errors += 1
textstring = oneLine
End If
Else
errors += 1
textstring = oneLine
End If
count += 1
Catch
errors += 1
textstring = oneLine
End Try
Next
End Using

Gettint text from lastline in richtextbox

I want to copy the last line of a rich textbox.
I am avoiding Dim lastLine As String = RichTextBox1.Lines(RichTextBox1.Lines.Length - 1)as
it's not working properly, as It works just if there are atleast 2 lines in it.
I'm trying with MsgBox(RichTextBox1.Lines(UBound(richtextbox1.Lines))) but the problem is that even if the richtextbox has just 1 line of text but the cursor is in the second empty line, it will give back "" as I think the software is reading the empty 2nd line.
There is a solution to that?
Thanks
This will get the last non-empty line:
RichTextBox1.Lines.Where(Function(line) line <> String.Empty).Last()
There are some potential issues with that. If there's no text at all or if there are multiple lines but they are all empty, that will throw an exception. To allow for that, you can call LastOrDefault instead, in which case it would return Nothing.
If you only want to exclude the last empty line, e.g. if you have some text followed by a line break and then another line break then you want to get the first of those two empty lines, then you can't really do it in one line:
Dim lines = RichTextBox1.Lines
Dim upperBound = lines.GetUpperBound(0)
Dim lastLine = lines(upperBound)
If lastLine = String.Empty Then
If upperBound > 0 Then
lastLine = lines(upperBound - 1)
Else
lastLine = Nothing
End If
End If
'Use lastLine here.

replace a line in richtextbox vb.net

I have this code but it have errors , what should i do ?
Dim lines As New List(Of String)
lines = RichTextBox1.Lines.ToList
'Dim FilterText = "#"
For i As Integer = lines.Count - 1 To 0 Step -1
'If (lines(i).Contains(FilterText)) Then
RichTextBox1.Lines(i) = RichTextBox1.Lines(i).Replace("#", "#sometext")
'End If
Next
RichTextBox1.Lines = lines.ToArray
Update: while the following "works" it does only modify the array which was returned from the Lines-property. If you change that array you don't change the text of the TextBox. So you need to re-assign the whole array to the Lines-property if you want to change the text(as shown below). So i keep the first part of my answer only because it fixes the syntax not the real issue.
It's not
RichTextBox1.Lines(i).Replace = "#sometext"
but
RichTextBox1.Lines(i) = "#sometext"
You can loop the Lines forward, the reverse loop is not needed here.
Maybe you want to replace all "#" with "#sometext" instead:
RichTextBox1.Lines(i) = RichTextBox1.Lines(i).Replace("#","#sometext")
So here the full code necessary (since it still seems to be a problem):
Dim newLines As New List(Of String)
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
newLines.Add(RichTextBox1.Lines(i).Replace("#", "#sometext"))
Next
RichTextBox1.Lines = newLines.ToArray()
But maybe you could even use:
RichTextBox1.Text = RichTextBox1.Text.Replace("#","#sometext")`
because if we have # abcd this code change it to # sometextabcd ! I
Want a code to replace for example line 1 completely to # sometext
Please provide all relevant informations in the first place next time:
Dim newLines As New List(Of String)
For Each line As String In RichTextBox1.Lines
Dim newLine = If(line.Contains("#"), "#sometext", line)
newLines.Add(newLine)
Next
RichTextBox1.Lines = newLines.ToArray()

How to delete a string from a RichTextBox?

I am trying to parse junk and narrow down a bunch of text. How do I delete the current line if a does not match? I would like to remove the line entirely:
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
Dim a As String = RichTextBox1.Lines(i).ToString
If Not a = "SaveThisLine" Then
'delete the active line
End If
Next
Also how would I match partially? Such as if not a = "SaveThisLine" & * (to use a wildcard).
I would not touch original text and rather save valid lines into a StringBuilder, so if line is valid, AppendLine to it. In the end dump back into RichTextBox1.Text using StringBuilder.ToString.
For partial match in VB.NET you can use a native Like operator:
"aaa" Like "a*"
Returns True.
Or use regular expressions:
System.Text.RegularExpressions.Regex.Match("aaa", "^a").Success
Also returns True.
You can do it in this way to:
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
If RichTextBox1.Lines(i) = "2" Then
RichTextBox1.Text = Replace(RichTextBox1.Text, RichTextBox1.Lines(i), "", , 1)
End If
Next

Search field in text file

I have some coding which displays a label if the value of a textbox matches any of the first values of each line in a textfile.
Dim sList As New List(Of String)(IO.File.ReadAllLines("Path"))
Dim i As Integer
For i = 0 To sList.Count - 1
If sList(i).StartsWith(textbox1.Text) Then
Label1.Visible = True
Exit For
Else
Label1.Visible = False
End If
Next
The problem is if the textbox has 1 and the textfile has 11 it will display the label, what would be the best way around this?
I have tried sList(i).Contains etc but none of them are doing the job.
I have tried all the suggestions here and nothing works, my textfile has numbers like the following
11
15
18
and for example if i have the number 1 in the textbox then the label is visible.
Try this:
Label1.Visible = IO.File.ReadAllLines("Path.txt").Any(Function(f) f = TextBox1.Text)
I think LINQ can be used here:
Dim text = textbox1.Text
Dim textWithSpace = String.Format("{0} ", text)
Label1.Visible = IO.File.ReadAllLines("Path").Any(Function(line) line.StartsWith(textWithSpace) OrElse line = text)
You need import System.Linq to make it work.
I assumed that space ends each word in the file.
If you want the Label to be visible when at least one of the lines starts with the text in the TextBox, you can use LINQ and Enumerable.Any:
Dim matchingLines = From l In IO.File.ReadLines("Path")
Where l.StartsWith(textbox1.Text)
Label1.Visible = matchingLines.Any()
Try changing the following line, assuming you are reading from a text file and looking for an exact match of the whole line you could try this:
If sList(i).StartsWith(textbox1.Text + Environment.NewLine) Then
That should check to make sure its the only thing on that line as it is now looking for a new line and will not match '11'