How to read Different lines of text in a RichTextBox - vb.net

I want to know how to read and convert the different lines of a richtextbox in vb.net
for example if these are the lines of a RichTextBox:
Hello
Hi
How can I convert it to something like:
Yo(Hello)
Yo(Hi)
and put the result in a second richtextbox?

RichtextBox has a lines property:
Dim rtb_in As New RichTextBox
Dim rtb_out As New RichTextBox
For Each line In rtb_in.Lines
rtb_out.AppendText(String.Format("Foo({0})", line))
Next
Always a good idea to check out MSDN for the classes you work with ...

You could try splitting on a new line and modifying the results:
Dim box1Lines as String() = richTextBox1.Text.Split(new String() { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
Dim newLines as String = ""
For Each line As String in box1Lines
newLines += "Yo(" & line & ")" & Environment.NewLine
Next
richTextBox2.Text = newLines

Possibly you should use String.Join to accomplish it. A one line solution would be:
rtbOut.Lines = ("Yo(" & String.Join(")" & Environment.NewLine & "Yo(", rtbIN.Lines) & ")").Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
and here is the complete code where modified line is assigned to second RichTextBox:
Dim rtbIN As New RichTextBox
Dim rtbOut As New RichTextBox
rtbIN.Lines = New String() {"Hello ", "Hi"}
rtbOut.Lines = ("Yo(" & String.Join(")" & Environment.NewLine & "Yo(", rtbIN.Lines) & ")").Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)

Related

Read message from text file and display in message box in vb.net

JavaError.128 = "project creation failed. & vbLf & Please try again and if the problem persists then contact the administrator"
I am able to read this message from text file. the issue is vbLf is not considered as newline in msgbox. it prints vbLf in msgbox.
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(errorfilePath)
While ((sr.Peek() <> -1))
line = sr.ReadLine
If line.Trim().StartsWith("JavaError." & output) Then
isValueFound = True
Exit While
End If
End While
sr.Close()
End Using
If isValueFound Then
Dim strArray As String() = line.Split("="c)
MsgBox(strArray(1).Replace("""", "").Trim({" "c}))
End If
You can make all your code a simpler one line version using File.ReadAllLines and LINQ. This code will put all the lines starting with javaerror into the textbox, not just the first:
textBox.Lines = File.ReadAllLines(errorFilePath) _
.Where(Function(s) s.Trim().StartsWith("JavaError")) _
.Select(Function(t) t.Substring(t.IndexOf("= ") + 2).Replace(" & vbLf & ", Environment.NewLine)) _
.ToArray()
You need to Imports System.IO and System.Linq
This code reads all the lines of the file into an array, then uses LINQ to pull out only those starting with java error, then projects a new string of everything after the = with vbLf replaced with a newline, converts the enumerable projection to an array of strings and assigns it to the textBox lines
If you don't want all the lines but instead only the first:
textBox.Text = File.ReadLines(errorFilePath) _
.FirstOrDefault(Function(s) s.Trim().StartsWith("JavaError")) _
?.Substring(t.IndexOf("= ") + 2).Replace(" & vbLf & ", Environment.NewLine))
This one uses ReadLine instead of ReadALlLines - ReadLines works progressively, and it makes sense to be able to stop reading after we foundt he first rather than have the overhead of reading ALL (million) lines only to then end up pulling the first out and throwing 999,999 lines of effort away. So it's reading line by line, pulls out the first that starts with "JavaError" (or Nothing if there is no such line), then checks if Nothing came out (the ?) and skips the Substring if it was Nothing, or it does a Substring on everything after the = and replaces vbLf with newline
For a straight up mod of your original code:
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(errorfilePath)
While ((sr.Peek() <> -1))
line = sr.ReadLine
If line.Trim().StartsWith("JavaError." & output) Then
isValueFound = True
line = line.Replace(" & vbLf & ", Environment.NewLine))
'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ added code
Exit While
End If
End While
sr.Close()
End Using
If isValueFound Then
Dim strArray As String() = line.Split("="c)
MsgBox(strArray(1).Replace("""", "").Trim({" "c}))
End If
Note that I've always made my replacement on & vbLf & with a space at each end to avoid stray spaces being left behind - if your file sometimes doesn't have them, consider using Regex to do the replace, e.g. Regex.Replace(line, " ?& vbLf & ?", Environment.NewLine
This could work:
Dim txtFile As String = "project creation failed. & vbLf & Please try again and if the problem persists then contact the administrator"
Dim arraytext() As String = txtFile.Split("&")
Dim txtMsgBox As String = Nothing
For Each row As String In arraytext
If Trim(row) = "vbLf" Then
txtMsgBox = txtMsgBox & vbLf
Else
txtMsgBox = txtMsgBox & Trim(row)
End If
Next
MsgBox(txtMsgBox)

Split multi line in VB

I have a problem in split multi line in that it only splits the first line. I want to split all the lines.
Dim a As String
Dim b As String
Dim split = TextBox1.Text.Split(":")
If (split.Count = 2) Then
a = split(0).ToString
b = split(1).ToString
End If
TextBox2.Text = a
TextBox3.Text = b
You have to iterate all the lines in the textbox
For Each Ln As String In TextBox1.Lines
If Not String.IsNullOrEmpty(Ln) Then
Dim Lines() As String = Ln.Split(":"c)
If Lines.Length = 2 Then
TextBox2.Text &= Lines(0) & Environment.NewLine
TextBox3.Text &= Lines(1) & Environment.NewLine
End If
End If
Next
Edit- Updated to include condition checking to prevent index exceptions.
Edi2- It should be mentioned that drawing your strings into these textbox controls can take some time, it's not my place to judge your requirement, but you could optimize the routine by using collection based objects or stringbuilder.
IE:
Dim StrBldrA As New Text.StringBuilder
Dim StrBldrb As New Text.StringBuilder
For Each Ln As String In TextBox1.Lines
If Not String.IsNullOrEmpty(Ln) Then
Dim Lines() As String = Ln.Split(":"c)
If Lines.Length = 2 Then
StrBldrA.Append(Lines(0) & Environment.NewLine)
StrBldrb.Append(Lines(1) & Environment.NewLine)
End If
End If
Next
TextBox2.Text = StrBldrA.ToString
TextBox3.Text = StrBldrb.ToString

Hard Time Writing NewLine in a .TXT File

Basically what I am doing is writing a program that pulls a quote from a website and writes it to a .txt file. It works fine except that I have no idea who to add NewLine into the .txt file. I will just show you the code.
If Not div Is Nothing Then
Dim blank As String = Environment.NewLine
Dim finish As String = (div.InnerText.Trim())
TextBox2.Text = Chr(34) & finish & Chr(34)
Dim fileName As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt")
My.Computer.FileSystem.WriteAllText(fileName, Chr(34) & finish & Chr(34), True)
My.Computer.FileSystem.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("userprofile"), "Documents\Horoscope\Monthly.txt"), blank, True)
My.Computer.FileSystem.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("userprofile"), "Documents\Horoscope\Monthly.txt"), blank, True)
End If
Now that works fine for the first pair of quotes, but anything after it does not indent due to another section of code that I have that deletes duplicates.
Dim lines As String() = IO.File.ReadAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"))
lines = lines.Distinct().ToArray()
IO.File.WriteAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"), lines)
Is there another way that I can get the same affect of having a gap inbetween my quotes in a text file?
When removing the duplicates, you can drop the existing blank lines with Where, then add them back into the lines array using SelectMany:
lines = lines.
Where(Function(x) Not String.IsNullOrEmpty(x)).
Distinct().
SelectMany(Function(x) { x, String.Empty }).
ToArray()
The SelectMany returns the line, plus a blank, for each line left after the Distinct.
You may also want to use File.AppendAllLines when adding new entries - seems a little cleaner:
File.AppendAllLines(fileName, { Chr(34) & finish & Chr(34), ""})
EDIT
This would fit in with your code something like this:
If Not div Is Nothing Then
Dim finish As String = (div.InnerText.Trim())
TextBox2.Text = Chr(34) & finish & Chr(34)
Dim fileName As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt")
IO.File.AppendAllLines(fileName, { Chr(34) & finish & Chr(34), ""})
End If
'...
Dim lines As String() = IO.File.ReadAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"))
lines = lines.
Where(Function(x) Not String.IsNullOrEmpty(x)).
Distinct().
SelectMany(Function(x) { x, String.Empty }).
ToArray()
IO.File.WriteAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"), lines)

VBNet Reading csv file - separating column in a row - comma delimited

This has been bugging me for a week and i do not see any other way. We have only been taught record data structures which is basic, FileOpen, WriteLine and etc. but i read MSDN and StreamWriter/Reader looks much more promising. This is an assignment/coursework and its essential for practically all parts of the program.
All i want to do is read line by line separating fields by a comma and define it as a variable. It would also help to be able to read the line without the quotes "", because right now when i read a password out with LineInput it reads it entirely "pass".
Private Sub StudentLogin()
Dim Filename As New StreamWriter("" & Register.StudentDirectory & "" & Username & ".txt")
Dim str As String = "This"
Dim lines() As String = str.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Firstname = columns(0)
Surname = columns(1)
Password = columns(2)
ClassID = columns(3)
Next
MessageBox.Show("" & ClassID & " " & Password & "")
End Sub
Text file:
"cem","polat","pass","class"
I just want to read the file - then each line, row by row, defining each column field which is in C:/Spellcheck/data/accounts/students/+filename+ and define a few variables.

How to find specified line in textbox

How to get an specified line in an textbox and get the text from that line in an string
Dim lines As String() = testing.Text.Split(Environment.NewLine)
then access the lines just like this
lines(0) // would be first line
You need to split the text box text into an array of strings based on the line separator and then, if you have enough lines, get the line from the array:
Dim asLines As String()
Dim wLineToGet As Integer = 2
asLines = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
If asLines IsNot Nothing AndAlso asLines.Length >= wLineToGet Then
MessageBox.Show("Line " & wLineToGet & " = " & asLines(wLineToGet - 1))
Else
MessageBox.Show("There are not enough lines in the textbox to retrieve line " & wLineToGet)
End If