Text file manipulation using visual basic - vb.net

Hi I am looking for a way to take a text file that has 1 set of numbers per line and make a new text file that has taken the set of numbers and put them into 2 spaced out columns per line. Using Visual Basic 2010 Ex:
My First text file will look similar to this: test1.txt
12345
23456
34567
45678
56789
67890
But I would like to convert it to look like this and save it as a new file: text2.txt
12345 23456
34567 45678
56789 67890
With more spacing in between the set of numbers. I have been struggling with this for about a week now and I have put myself back at square one with it. Thank you all for your time and hope you all have a good day. Joe.
Here is my current code. I am embarrassed to say the least. I am taking an exsisting file and formatting it to have a space between each line of numbers and then reading it into a richtextbox to convert it to a barcode font then saving it. At that point I have no idea how to make the format the way I need it to be putting 2 sets of numbers on one line.
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnLoad.Click
ListBox1.Items.AddRange(IO.File.ReadAllLines("C:\test\serintest.txt"))
End Sub
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnConvert.Click
Dim FILE_NAME As String = "C:\test\serscantemp.rtf"
Dim i As Integer
Dim t As Integer
TextBox1.Text = ListBox1.Items.Count.ToString(t)
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
For i = 0 To TextBox1.Text - 1
'objWriter.WriteLine(aryText(i))
objWriter.WriteLine(ListBox1.Items(i))
objWriter.WriteLine("")
Next
objWriter.Close()
Me.RichTextBox.LoadFile("C:\test\serscantemp.rtf", _
RichTextBoxStreamType.PlainText)
RichTextBox.SaveFile("c:\test\barcodetext.rtf", _
RichTextBoxStreamType.RichText)
End Sub

Joe,
Try this.
I am concatenating the numbers into a string variable and keeping a counter. If the counter = 2 then i write out the concatenated string to RichTextBox and clear counter and string variable
Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
Dim FILE_NAME As String = "C:\temp\serscantemp.rtf"
Dim i As Integer
Dim t As Integer
Dim s As String
Dim c As Integer
TextBox1.Text = ListBox1.Items.Count.ToString(t)
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
c = 0
s = ""
For i = 0 To TextBox1.Text - 1
c = c + 1
If s > "" Then
s = s & " "
End If
s = s & ListBox1.Items(i)
If c = 2 Then
objWriter.WriteLine(s)
objWriter.WriteLine("")
s = ""
c = 0
End If
'objWriter.WriteLine(aryText(i))
Next
objWriter.Close()
RichTextBox1.LoadFile("C:\temp\serscantemp.rtf", _
RichTextBoxStreamType.PlainText)
RichTextBox1.SaveFile("c:\temp\barcodetext.rtf", _
RichTextBoxStreamType.RichText)
End Sub
I hope this is what you are looking for.

Here's another way to do it that you might also want to try though almost the same as Ed's answer. Just call the routine from btnConvert click event. Also make sure to include Import System.IO
Private Sub Reformat(sourceFile As String, destFile As String)
Dim arr As String() = File.ReadAllLines(sourceFile)
Dim s As String = String.Empty
Dim lst As New List(Of String)()
Dim iCtr As Integer = 0
For i As Integer = 0 To arr.Length - 1
If Not String.IsNullOrWhiteSpace(arr(i)) Then
s += arr(i) & " "
iCtr += 1
If iCtr = 2 Then
lst.Add(s.Trim())
iCtr = 0
s = String.Empty
End If
End If
Next
If Not String.IsNullOrWhiteSpace(s.Trim()) Then
lst.Add(s)
End If
File.WriteAllLines(destFile, lst.ToArray())
End Sub
By the way, this is my first post in SO. Just saying.

Related

Read each number from array and making sum

I am kinda new at coding.
I am reading some numbers from a txt files and i have them into a array,i managed to make them descending,now i want to make a sum with this numbers,for example:
I will have an input number 1000,on the list i will have numbers from 100 to 1000 and i want to make a sum with them to reach 1000 with minimum rest.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fStream As New System.IO.FileStream("C:\Users\Alex\Desktop\test.txt", IO.FileMode.Open)
Dim sReader As New System.IO.StreamReader(fStream)
Dim List As New List(Of Double)
Do While sReader.Peek >= 0
List.Add(sReader.ReadLine)
Loop
Dim i As Long
Dim txt As String
Dim thisArray As Double() = List.ToArray
For i = LBound(thisArray) To UBound(thisArray)
txt = thisArray(i) & vbCrLf
Next i
Array.Sort(thisArray)
For j As Integer = 0 To thisArray.Count - 1
Dim FILE_NAME As String = "C:\Users\Alex\desktop\test2.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, IO.FileMode.Append)
objWriter.WriteLine(thisArray(j))
objWriter.Close()
Else
MessageBox.Show("File Does Not Exist")
End If
Next
fStream.Close()
sReader.Close()
End Sub
I dont know where to start to do this..input number will be from a textbox.

How to get line number from a text file in vb.net

I am making a program where i have 2 text files and i want 2 get one line from each text file like this
Dim pathlocal as string= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Test\"
Dim reader As New System.IO.StreamReader(pathlocal & "to.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
For Each file In allLines
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(file).Name) Then
'Get line number of from.txt where you found file.name
End If
End If
Next
I appreciate the help(and pls try 2 make it simple sorry but i am not that good THANX)
This might help you:
Imports System.IO
Imports System
Imports System.Collections.Generic
Public Class Form1
Dim path As String = "Your Path"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim indxto As Integer = 0
Dim indxfrom As Integer = 0
Dim allLinesto As List(Of String) = File.ReadAllLines(path & "\" & "to.txt").ToList
Dim allLinesfrom As List(Of String) = File.ReadAllLines(path & "\" & "from.txt").ToList
For Each line As String In allLinesto
indxto = allLinesto.IndexOf(line)
'Debug.Print(line & " " & indxto.ToString)
For Each item As String In allLinesfrom
indxfrom = allLinesto.IndexOf(item)
If line = item Then
Debug.Print(item & " " & indxfrom.ToString)
End If
Next
Next
End Sub
End Class
You can instantiate a couple of Integer typed variables to help with this. One stores the line number as you iterate through the list and the other stores the line number you are seeking. Plus, by changing your For Each approach to a Do Until or Do While approach you could potentially speed things up if the target is found prior to the last line of the file.
Dim intLineNumber As Integer = -1
Dim intLineCursor As Integer
Do Until (intLineCursor = allLines.Count OrElse intLineNumber <> -1)
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(allLines(intLineCursor)).Name) Then
intLineNumber = intLineCursor '+ 1 if you are displaying to a user since the lower bound is 0 based.
End If
'Increment the cursor variable.
intLineCursor += 1
Loop

How to make a program that would detect the same characters within two strings

so i made this but when i enter a string it would only detect one character
and it wont convert the entered string to lower case too
Dim readme, readme2 As String
Dim j, i As Integer
Dim Compare As Integer
readme = TextBox1.Text
readme2 = TextBox2.Text
readme.ToLower.Substring(i, readme.Length)
readme2.ToLower.Substring(j, readme2.Length)
For i = 0 To readme.Length
For j = 0 To readme2.Length
If readme = readme2 Then
Compare = +1
End If
Next
Next
Label4.Text = Compare`enter code here`
Strings are immutable. You cannot apply a method to a string and expects that string to change in response to the inner operations of that method.
You need to reassign the result of the operation to the same string that you have used to call the method
readme = readme.ToLower()
readme2 = readme2.ToLower()
The second part of your question is more confused, are you trying to count the number of equal chars in the same position?
In that case your loop should be
Dim maxLenToCheck = Math.Min(readme.Length, readme2.Length)
For i = 0 To maxLenToCheck - 1
If readme(i) = readme2(i) Then
Compare += 1
End If
Next
In that loop you set always the Compare to 1, the correct syntax to increment the Compare variable is
Compare += 1
Following your comment below, then I presume that your loop should be written as
Dim Compare = 0
For i = 0 To readme.Length - 1
for j = 0 to readme2.Length -1
If readme(i) = readme2(j) AndAlso _
Not Char.IsWhiteSpace(readme(i)) Then
Compare += 1
End If
Next
Next
Based on the comments in the solution by Steve, the author wants to know the count of letters occurring in both strings, ignoring case and white spaces.
By my count, however, the solution should be 21, not 20. Here is a solution using LINQ that also gives visual feedback on where those letters are located:
Public Class Form1
Private Class LetterCount
Public Letter As Char
Public Count As Integer
Public Overrides Function ToString() As String
Return Letter & " : " & Count
End Function
End Class
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "This is a Test"
TextBox2.Text = "This should be tryed before"
RichTextBox1.ReadOnly = True
RichTextBox1.Font = New Font("MS Courier", 14) ' monospaced font
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = TextBox1.Text & vbCrLf & TextBox2.Text & vbCrLf
Dim charsA As New List(Of Char)(TextBox1.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim charsB As New List(Of Char)(TextBox2.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim DistinctCommonLetters = (From A In charsA, B In charsB Where A = B Select A).Distinct
Dim DistinctCounts =
From Letter In DistinctCommonLetters, C In charsA.Concat(charsB)
Where C = Letter
Group By Letter Into Group
Select New LetterCount With {.Letter = Letter, .Count = Group.Count}
Dim TotalMatches = DistinctCounts.Sum(Function(x) x.Count)
ListBox1.DataSource = DistinctCounts.ToList
Label1.Text = "TotalMatches: " & TotalMatches
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim LC As LetterCount = ListBox1.SelectedItem
RichTextBox1.SelectAll()
RichTextBox1.SelectionColor = Color.Black
Dim index As Integer = RichTextBox1.Find(LC.Letter, 0, RichTextBoxFinds.None)
While index <> -1
RichTextBox1.Select(index, 1)
RichTextBox1.SelectionColor = Color.Red
index = RichTextBox1.Find(LC.Letter, index + 1, RichTextBoxFinds.None)
End While
End Sub
End Class

VB.net multithreading for loop, parallel threads

I have a simple form with 2 RichTextBoxes and 1 button, the code grabs the url address from RichTextBox1 and phrases the page for the title field using regex and appends it to RichTextBox2. I want to multithread everything in such way that none of the url's are skipped and the thread numbers can be set ( according to the system free resources ) For example, let's say 10 threads to run in parallel. I searched everything and the best that I managed to do is run everything in a background worker and keep the GUI from freezing while working. A short code sample will be of much help, I am a beginner in VB.net.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 0 To RichTextBox1.Lines.Length - 1
If RichTextBox1.Lines(i).Contains("http://") Then
Dim html As String = New System.Net.WebClient() _
.DownloadString(RichTextBox1.Lines(i))
Dim pattern As String = "(?<=\<title\>)([^<]+?)(?=\</title\>)"
Dim match As System.Text.RegularExpressions.Match = _
System.Text.RegularExpressions.Regex.Match(html, pattern)
Dim title As String = match.Value
RichTextBox2.AppendText(title & vbCrLf)
End If
Next
End Sub
End Class
Updated code ( throwing "Index was outside the bounds of the array." errors. )
Imports System
Imports System.Threading
Public Class Form1
Public Sub test(ByVal val1 As String, ByVal val2 As String)
Dim zrow As String
zrow = RichTextBox1.Lines(val1)
If zrow.Contains("http://") Then
Dim html As String = New System.Net.WebClient().DownloadString(zrow)
Dim pattern As String = "(?<=\<title\>)([^<]+?)(?=\</title\>)"
Dim match As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(html, pattern)
Dim title As String = match.Value
RichTextBox2.AppendText(val2 & title & vbCrLf)
End If
End Sub
Public Sub lastfor(ByVal number)
Dim start As Integer = number - 100
For x = start To number - 1
Try
test(x, x)
RichTextBox2.AppendText(x & RichTextBox1.Lines(x).Trim & vbCrLf)
Catch ex As Exception
'MsgBox(ex.Message)
RichTextBox3.AppendText(ex.Message & vbCrLf & vbCrLf)
End Try
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim TotalLines As String = RichTextBox1.Lines.Length - 1
Dim TotalThreads As Integer = 10
Dim LinesPerThread As Integer = TotalLines / TotalThreads
Dim increment As String = LinesPerThread
Dim zdata(TotalThreads) As String
For i = 0 To TotalThreads - 1
zdata(i) = increment
increment = increment + LinesPerThread
Next
Dim lst As New List(Of Threading.Thread)
For Each bump As String In zdata
Dim t As New Threading.Thread(Function(l As String)
'Do something with l
'Update GUI like this:
If bump = String.Empty Or bump Is Nothing Then
Else
lastfor(l)
'MsgBox(l)
End If
End Function)
lst.Add(t)
t.Start(bump)
Next
'test(1)
End Sub
End Class
There are two ways two achieve this:
First, if you are using .NET 4.0, you could use a Parallel.ForEach loop:
Parallel.ForEach(RichTextBox1.Lines, Function(line As String)
' Do something here
' To update the GUI use:
Me.Invoke(Sub()
' Update GUI like this...
End Sub)
Return Nothing
End Function)
The other way is to do this manually (and you will have slightly more control):
Dim lst As New List(Of Threading.Thread)
For Each line In RichTextBox1.Lines
Dim t As New Threading.Thread(Function(l As String)
'Do something with l
'Update GUI like this:
Me.Invoke(Sub()
'Update Gui...
End Sub)
End Function)
lst.Add(t)
t.Start(line)
Next
Both of these are very crude, but will get the job done.
EDIT:
Here is a sample code that will control the number of threads:
Dim lst As New List(Of Threading.Thread)
Dim n As Integer = 1 ' Number of threads.
Dim npl As Integer = RichTextBox1.Lines / n
Dim seg As New List(Of String)
For Each line In RichTextBox1.Lines
For i = npl - n To npl
seg.Add(RichTextBox1.Lines.Item(i))
Next
Dim t As New Threading.Thread(Function(l As String())
For Each lin In l
' TO-DO...
Next
'Do something with l
'Update GUI like this:
Me.Invoke(Sub()
'Update Gui...
End Sub)
End Function)
lst.Add(t)
t.Start(seg.ToArray())
Next
*The above code might have bugs.

Selecting text in vb

I want to select a word to another word in a text box in vb.net with everything between them highlighted.
an example is
I went to the beach, had a pinic with my family and then went home at 6 o clock.
The starting word to be had and the end word being home and everything highlighted in between.
I have already used a little bit of code
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim a As String
Dim b As String
a = TextBox2.Text 'means what ever is in textbox2 string to the location where "a" is
b = InStr(RichTextBox1.Text, a)
If b Then
RichTextBox1.Focus()
RichTextBox1.SelectionStart = b - 1
RichTextBox1.SelectionLength = Len(a)
but its not exactly what i want it to do.
Addition to this was using RegEx Function as shown below
'gets rid of the enter line break eg <enter> command no new lines
Dim content As String = Replace(TextBox1.Text, Global.Microsoft.VisualBasic.ChrW(10), Nothing)
'searches for this tag in the brackets between ".*" will be the contents
Dim Regex As New Regex("<div.*class=""answer_text"".*id=editorText"".*""")
'Show the string
For Each M As Match In Regex.Matches(content)
'This will get the values, there are 3 atm meta.name des and content
Dim Description As String = M.Value.Split("""").GetValue(3)
'displays the content in the label
TextBox3.Text = "" & Description
Next
This will select everything between startWord and endWord excluding them both
Dim startWord As String = "had"
Dim endWord As String = "home"
Dim index As Integer = richTextBox1.Text.IndexOf(startWord)
richTextBox1.[Select](index + startWord.Length, richTextBox1.Text.IndexOf(endWord) - index - startWord.Length)
Here's a solution involving two TextBox controls:
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim a As String
Dim b As String
Dim index_a As Integer
Dim index_b As Integer
a = TextBox1.Text
b = TextBox2.Text
index_a = InStr(RichTextBox1.Text, a)
index_b = InStr(RichTextBox1.Text, b)
If index_a And index_b Then
RichTextBox1.Focus()
RichTextBox1.SelectionStart = index_a - 1
RichTextBox1.SelectionLength = (index_b - index_a) + Len(b)
End If
End Sub
TextBox1 contains the first word, TextBox2 contains the second word. When clicking the button, it will highlight from the first word to the end of the second word.