Overwrite text file between parameters [ and ] - vb.net

I would like for example to modify in the text file only what is written between [newtext] 103 and [endtext] 103 , from my textbox.
[newtext]101
This is a first demonstration
This is a message
of Hello World
[endtext]101
[newtext]102
This is a 2nd demonstration
This is a 2nd message
of Hello World
[endtext]102
[newtext]103
This is a 3nd demonstration
This is a 3nd message
of Hello World
[endtext]103
so if I have text in my textbox
This is a newest demonstration
This is a newest message
of Hello World
how do I adapt to replace file the old text with the new text? that is, the output will be:
attention, the other values between [newtext] 101, [newtext] 102, will not be erase.
[newtext]103
This is a newest demonstration
This is a newest message
of Hello World
[endtext]103
this is a code, but unfortunately it has to find the values ​​between the chosen parameters.
Dim text As String = File.ReadAllText(My.Application.Info.DirectoryPath + ("\Data.txt"))
text = text.Replace(TextBox1.Text, TextBox2.Text)
File.WriteAllText("Data.txt", text)

ReadAllLines returns an array of the lines in the text file. The get the index of the line with the search text. Then get an array of the lines in the TextBox1. Simply assign the new text to the proper indexes in the lines in the file. Lastly, I displayed the new string TextBox2.
Be sure that both text boxes are wide enough to display the lines and have Multiline = True.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileLines = File.ReadAllLines("C:\Desktop\Code\DemoMessage.txt")
Dim lineToFind = "[newtext]103"
Dim index = Array.IndexOf(FileLines, lineToFind)
Dim tbLines = TextBox1.Lines
FileLines(index + 1) = tbLines(0)
FileLines(index + 2) = tbLines(1)
FileLines(index + 3) = tbLines(2)
TextBox2.Text = String.Join(Environment.NewLine, FileLines)
'you can write the contents of TextBox2 back to file if needed.
End Sub

Related

How can calculate the number of columns in a textfile and show in a textbox, in vb.net?

I have a textfile (data.txt) with 3 columns, each column with one variable (x1, x2 and x3). I would like to calculate a number of columns and show in a specific textbox (like textbox1).
For example. My data.txt:
x1 x2 x3
10 15 20
20 10 10
TextBox1 needs to show: 3
Text files don't have columns. What you have is a file where each line separates elements by a space and each row is separated by a CR/LF (carraige return/line feed) To work with the text file put
Imports System.IO
at the top of the code file.
I am guessing that you will want to do more with the file than just determin the number of "columns" so, we will read the entire file. File.ReadAllLines() returns an array of lines in the file.
We take the first line in the file (index 0) and split it by a space. The lowere case c followint " " tells the compiler that you mean a Char not a String. Then we take the Length of the resulting array to find the number of columns.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines = File.ReadAllLines("C:\Users\******\Desktop\Code\OPdata.txt")
Dim NoOfColumns = lines(0).Split(" "c).Length
TextBox1.Text = NoOfColumns.ToString
'Some other things you can do
Dim dt As New DataTable
Dim columns = lines(0).Split(" "c)
dt.Columns.Add(columns(0), GetType(Integer))
dt.Columns.Add(columns(1), GetType(Integer))
dt.Columns.Add(columns(2), GetType(Integer))
For index = 1 To lines.Length - 1
Dim values = lines(index).Split(" "c)
dt.Rows.Add({values(0), values(1), values(2)})
Next
DataGridView1.DataSource = dt
End Sub
You might want to consider using Microsoft.VisualBasic.FileIO.TextFieldParser. It's designed to process structured text files (either delimited or fixed-width) and will remove some of the necessary ceremony compared with direct file I/O as in Mary's answer. Note that TextFieldParser implements IDisposable, so it should either be used within a Using block or disposed manually.
FileOpen(1, "data.txt", OpenMode.Input)
line1$ = LineInput(1) 'get first line
FileClose(1)
TextBox1.Text = UBound(Split(line1, " ")) + 1

String Concatenation with Comma and Single Quotes E.g. ('ABC','DEF','GHI,'JKL')

I've been searching on internet how to Concatenate/Join Single quotes and comma on the String in vb.net's RichTextBox control. Example ('ABC','DEF','GHI,'JKL') I found this code online today it works even there's leading and trailing spaces and even lines are removed but the (' and ') are missing. Can you guys modify the code?
Code:
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text.Trim, "\s+", "','")
Inside the RichTextBox1
ABC
DEF
GHI
JKL
Result: ABC','DEF','GHI','JKL
Desired Result: ('ABC','DEF','GHI','JKL')
As you can see, there are multiple ways this could be done. Here's another:
myRichTextBox.Text = $"('{String.Join("'," & ControlsChars.Lf & "'", myRichTextBox.Lines)}')"
Note that I have used ControlChars.Lf where I would usually use Environment.NewLine because the RichTextBox always uses that line break. I assume that it has something to do with the RTF format and compatibility.
Give this a try
' starting RichTextBox1 contains
' ABC
' DEF
' GHI
' JKL
Dim lns() As String = RichTextBox1.Lines
For x As Integer = 0 To lns.Length - 1
lns(x) = String.Format("'{0}',", lns(x))
Next
lns(0) = "(" & lns(0)
lns(lns.Length - 1) = lns(lns.Length - 1).TrimEnd(","c)
lns(lns.Length - 1) &= ")"
RichTextBox1.Lines = lns
Not knowing how many lines you are dealing with in a real scenario, I chose to use a StringBuilder. It creates mutable (changeable) strings saving us throwing away and recreating strings many times.
Start off the sb with the initial "(". Then the loop uses an interpolated string with an embedded variable for each line. AppendLine will add a new line after the text.
Lastly we display the new string. In .net we can string the dot notation working left to right. First convert the StringBuilder back to an actual String with .ToString. Next we clean up the end of the new string by removing the final comma and the final new line. A new line is actually composed of 2 Chars, carriage return and line feed. Lastly I added the final ")"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines() = File.ReadAllLines("some text file path")
Dim sb As New StringBuilder
sb.Append("(")
For Each line In lines
sb.AppendLine($"'{line}',")
Next
RichTextBox1.Text = sb.ToString.Trim({","c, Convert.ToChar(13), Convert.ToChar(10)}) & ")"
End Sub

Read every fourth line from a text file

So, I have a text file with the following:
Andrew Law
0276376352
13 Parsons St
Kevin Kyle
0376458374
29 Penrod Drive
Billy Madison
06756355
16 Stafford Street
Now on my Form, I have a ListBox. When the Form loads, I would like to read every fourth line from the text file (every name) and display it in the ListBox.
All I have right now is the following:
Dim People As String
People = System.IO.File.ReadAllLines("filelocation")(3)
ListBox1.Items.Add(People)
This however only reads line number 4 where as I want to read EVERY fourth line after that also.
Add all the strings extracted from a source file, when the current line is a multiple of a pre-defined number of lines to skip or 0, to a ListBox and allow a user to select a Name from the list to fill some Labels with the details related to the selected Name.
Parse and extract the People Names from the array of string. Each Name can be found at an index which is multiple of the value specified by the skipLines field.
Add each Name to a ListBox control.
When a Name is selected from the ListBox list of names, add the related details to some Labels (named lblPhoneNumber and lblAddress here). To identify the correct informations in the array, we're using the skipLines value as a multiplier this time. This way, even if you add some more details in the list of names, you'll find the right informations modifying just the skipLines value.
You need to subscribe to the SelectedIndexChanged event of the ListBox:
Public Class Form1
Private people As String()
Private skipLines As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
skipLines = 3
people = File.ReadAllLines([Source File])
For line As Integer = 0 To people.Length - 1
If line Mod skipLines = 0 Then
ListBox1.Items.Add(people(line))
End If
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim StartIndex As Integer = ListBox1.SelectedIndex * skipLines
lblPhoneNumber.Text = people(StartIndex + 1)
lblAddress.Text = people(StartIndex + 2)
End Sub
End Class
How this works:
Define the number of lines to skip. We want a line of text, then skip 3 lines, here:
Dim skipLines As Integer = 3
We create an array of strings. It will contain the output of File.ReadAllLines(), which of course returns an array of strings:
Dim people As String() = File.ReadAllLines([Source File])
Iterate the whole content of the array of strings, line by line. A collection enumeration starts from 0, so we parse the list from 0 to the number of elements - 1:
For line As Integer = 0 To people.Length - 1
'[...]
Next
The If condition if met when the current line number is a multiple of skipLines.
The Mod operator divides two numbers and returns the remainder of the operation. If there's no reminder, the line number is a multiple of skipLines, the number of lines we want to skip.
If line Mod skipLines = 0 Then
`[...]
End If
Finally, when the condition is met, add the content of the array of strings (the people array) at the index represented by the current line value, to the ListBox.Items collection:
ListBox1.Items.Add(people(line))

VB windows form calculate the digit in a multiline textbox

I want to calculate each line: it's like first line 123*1.616 and the second line 213*1.616, and display each total.
Every number entred in the kilogram textbox will mutiply 1.616 and then show the result in the kati label.
Here is my code:
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Enter
For Each digit In (TextBox1.Text)
total1 = Val(digit) * 1.616
Label9.Text = total1
Next
Label9.Text = total1
End sub
Please help me find some solution or explanation to achieve the output.
This should work
Private FACTOR As Decimal = 1.616
Private SEPARATOR As String = Environment.NewLine
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
Label9.Text = TextBox1.Text.
Split({SEPARATOR}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(s1) $"{Decimal.Parse(s1) * FACTOR:0.00#}").
Aggregate(Function(s1, s2) $"{s1}{SEPARATOR}{s2}")
End Sub
Here are the functions in the LINQ
Split makes an array out of each line in the TextBox using SEPARATOR as the delimiter
Select transforms the elements into their value times FACTOR
Aggregate puts the elements back together into a SEPERATOR delimited string
Why didn't your original code work?
You were iterating over each char in the text, and multiplying the char by a float (Option Strict On, as suggested in the comments would have prevented that).
Then in each iteration, you do (simplified) Label9.Text = Val(digit) * 1.616 which overwrites the Label every time.
If you were to step through in debug (also suggested in comments), you would see the Label becoming 1x1.616=1.616, 2x1.616=3.232, 3x1.616=4.848, etc. The result was the very last character in your TextBox, '3', times 1.161 = 4.848. Obviously, this was not what you wanted. You needed to instead iterate over each entire number. The multiline TextBox separates each line with a new line. So we iterate over each line instead.
you can use split string by vbCrLf
Sub main()
Dim multilinetext As String =
"10
20
30
40
50
60"
Dim number_array = multilinetext.Split(vbCrLf)
Dim output As Integer = 0
For Each i In number_array
output += i
Next
Stop
End Sub

How to find and delete matching words in two different text files in VB?

Its a wordy question, but basically I want to have VB check textfile1 for matching words in textfile2, and then delete all instances of similar words in textfile2 and output the results as results.txt.
Outputting results shouldn't be too difficult, but i'm unsure on where to proceed when it comes to recognizing similar wordage. Also, would it be possible to set up a whitelist (there's going to be one word repeated over and over - which I don't want deleted).
This is my open file / read file dialogue which I use for both prompts, and both are displayed visually in a textbox.
Sub Maplist()
If txtFile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim sr As New System.IO.StreamReader(txtFile.FileName)
tbx1.Text = sr.ReadToEnd
sr.Close()
End If
Thanks for any help!
Edit:
A sample of the first text file looks like this:
map_01, 200/250
map_03, 358/450
map_06, 528/2000
The second file looks like:
map_01
map_02
map_03
map_04
map_05
map_06
Basically the second file is the "master list'. I want the program to recognize a matching word between both files (for instance, the 01 in map_01) and then delete the entry from the master list. When I was talking about whitelisting I was concerned that it would match a word like"map" and delete everything in the master list. I didn't wanted it to delete the whole word just because it matched "map"
You have to make an array of words from both the TextFile and compare those. I did it for you here:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'make array of words from both the files
Dim text1Array() As String = TextBox1.Text.Split(" ")
Dim text2Array() As String = TextBox2.Text.Split(" ")
Dim NewText As String
NewText = TextBox2.Text
'loop through all the words in first array
For i = 0 To text1Array.Length - 1
'loop through all the words in second array
For j = 0 To text2Array.Length - 1
'match the words
If text1Array(i) = text2Array(j) Then
'replace the found word with an empty character
NewText = NewText.Replace(text2Array(j), String.Empty)
'delete double space
NewText = NewText.Replace(" ", " ")
End If
Next
Next
'save it into third textbox
TextBox3.Text = NewText
End Sub
I checked it like this:
Textbox1 contained :
one two three four five six seven eight nine ten eleven twelve
TextBox2 contained :
one subaz three sarma five loves six coding eight ten all the twelve time
After clicking the button, TextBox3 contained:
subaz sarma loves coding all the time
This works perfectly fine.
Now, about the whitelist, let's say you don't want to remove "five" even if it's matched. Do this:
Dim WhiteListWord As String = "five"
And change the condition as :
If text1Array(i) = text2Array(j) And text1Array(i) <> WhiteListWord Then
New output in the textbox3 will be :
subaz sarma five loves coding all the time