Populating a combo box with the first word of a textfile - vb.net

So I feel like im pretty close, but I also have a feeling I am mixing up StreamReader and ReadAllLines
....................................................................................
Option Strict On
Imports System.IO
Public Class Form4
Dim file As System.IO.StreamWriter
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
file = My.Computer.FileSystem.OpenTextFileWriter("c:\devices.bat", False)
file.WriteLine("#echo off")
file.WriteLine("cd " & Form1.TextBox2.Text)
file.WriteLine("adb devices > C:\devices.txt")
file.Close()
Shell("C:\devices.bat", AppWinStyle.Hide, True, 500)
Dim output() = System.IO.File.ReadAllLines("C:\deviceinfo2.txt")
Dim Devices As String = ""
Dim line() As String = {}
For X = 1 To output.Count = -1
line = output(X).Split(New Char() {(" ")})
Devices = line(0)
ComboBox1.Items.Add(Devices)
Next
output.Close()
output.Dispose()
End Sub
End Class
........................................................................
What I am trying to have it do is to start reading on line two of devices.txt and then read the first word from each line until the text file is done.
It seems simple enough, but like I said, I think I am mixing streamreader with readalllines
Any help is appreciated

Class Test
Public Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As New StreamReader("TestFile.txt")
Dim line, firstWord As String
Dim i as Integer = 0
' Read and display lines from the file until the end of
' the file is reached.
Do
line = sr.ReadLine()
If Not (line Is Nothing) AndAlso i > 0 Then
firstWord = line.Split(" ")(i)
'do your logic
End If
i += 1
Loop Until line Is Nothing
End Using
Catch e As Exception
' Let the user know what went wrong.
End Try
End Sub
End Class
Grabbed this from MSDN and modified it. It should compile, but I didn't test it. This will loop through the lines, 1 by 1, skip the first line and grab each line's first word after. Hope this helps.

Related

Getting strings from a textfile in a combobox, vb.net

Here is my code :
I'm trying to have some value out from a TXT file to a combobox or label but i feel combobox would be easier.
here's my code :
please note, some config.txt will only have 1 value while other 5-6
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IDinFile As String
Dim ID As String
If IO.File.Exists("config.txt") Then
Using StreamReader As New IO.StreamReader("config.txt")
Do
IDinFile = StreamReader.ReadLine
If (IDinFile.IndexOf("7656")) <> -1 Then
ID = IDinFile.Substring(2)
ID = ID.Trim().Remove(ID.Length - 1)
ComboBox1.Items.Add(ID)
Exit Do
End If
Loop Until IDinFile Is Nothing
End Using
End If
End Sub
the file here in .png :
https://i.stack.imgur.com/iYaqP.png
Re-written the code for you. Problem was wrongly placed Exit Do. Also, its advisable to check the line before entering the loop rather than at the end of the loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IDinFile As String
Dim ID As String
Const FILENAME As String = "config.txt"
If IO.File.Exists(FILENAME) Then
Using StreamReader As New IO.StreamReader(FILENAME)
Do While StreamReader.Peek() >= 0
IDinFile = StreamReader.ReadLine.Trim()
If (IDinFile.IndexOf("7656")) <> -1 Then
ID = IDinFile.Substring(1, IDinFile.Length - 2)
ComboBox1.Items.Add(ID)
End If
Loop
End Using
End If
End Sub
After you add the first item to the combobox you have an Exit Do statement. It no longer continues checking further lines and adding them to the combobox.
You should remove that statement.
Try this. It'll work if the values are organized line by line in the txt file.
Dim srd as New StreamReader("config.txt")
If io.file.exists("config.txt") then
Dim str() = srd.ReadToEnd.split(environment.newline)
For i = 0 to str.count-1
Combobox.item.add(str(i))
Next
srd.close

Advanced Replacement Freeze

Basically I'm creating a tool which while is looking through lines of "file.txt" to replace a word from a textbox's content with that line if the line is containing that word.
Basically if the line is: pizza-cheese-potatoes, all the words containing "pizza" or "cheese" or "potatoes" to be replaced with "pizza-cheese-potatoes"
Here is what I have until now. But it freeze and I don't really know why. Please help me. :)
Dim PATH As String = "C:\test.txt"
Sub Repl(x As String)
For Each line As String In File.ReadLines(PATH)
Dim myList = New List(Of String)(line.Split("|"c))
For Each item As String In myList
If x Is item Then
TextBox1.Text.Replace(x, line)
End If
Next
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each word As String In TextBox1.Text.Split(" "c)
Repl(word)
Next
End Sub
Thank you in advance!
Try doing it like this instead.
Public Sub DoWork()
Dim lines = IO.File.ReadAllLines(PATH)
For Each line In lines
Dim myList = New List(Of String)(line.Split("-"c))
For Each item In myList
If TextBox1.Text.Contains(item) Then
TextBox1.Text = TextBox1.Text.Replace(item, line)
End If
Next
Next
End Sub
Your reader reads the file multiple times which is massively inefficient. This code reads it once, then we just loop over each line with no need to worry about exit conditions etc.
However it's not really doing anything useful as you're not pausing after each line so you'll only be able to review the final one.
There is also no need to test if the textbox contains the text, just simply do a replace then you only search the text once.
For Each item In myList
TextBox1.Text = TextBox1.Text.Replace(item, line)
Next
-------- edit --------
To fix the issue with replacing the word you've already replaced you could try using a replacement placeholder.
For Each item In myList
TextBox1.Text = TextBox1.Text.Replace(item, "#")
Next
TextBox1.Text = TextBox1.Text.Replace("#", line)
---------- edit 2 ------------------
You want to try and build up a new string, word by word, instead of replacing the text in the textbox. This is so that words you've substituted already don't get converted.
Function ReplaceWord(word As String, lines As String())
For Each line As String In File.ReadLines(PATH)
Dim myList = New List(Of String)(line.Split("|"c))
For Each item As String In myList
If word = item Then
Return line
End If
Next
Next
Return word
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim result As New System.Text.StringBuilder
Dim lines = File.ReadLines(PATH)
For Each word As String In TextBox1.Text
result.Append(ReplaceWord(word, lines)).Append(" ")
Next
Textbox1.Text = result.ToString()
End Sub

HI, New to programming with textfiles loops and much more

i have a textfile which is in this format
and i am trying to use a stream reader to help me loop each word into a text box, i am new to programming and really need help because all other examples are too complicated for me to understand,
this is what i am trying to do :
Dim objectreader As New StreamReader("filepath")
Dim linereader(1) As String
linereader = Split(objectreader.ReadLine, ",")
For i As Integer = 0 To UBound(linereader)
Spelling_Test.txtSpelling1.Text = linereader(0)
Spelling_Test.txtSpelling2.Text = linereader(0)
Next
but only get the first line of the text file in to a textbox, i need it to loop to the next line so i can write the next line in!
your help would be much appreciated, and if possible then can you show it practically , if you dont understand what i am trying to do then please ask
It is a little confusing on what you are trying to do, it looks like your text file consists of a word and a hint, you only have one set of textbox's and 3 lines of information in your file.
This example show you how to incrementally read your Stream.
Public Class Form1
Dim objectreader As StreamReader
Dim linereader() As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If IsNothing(objectreader) Then
objectreader = New StreamReader("C:\Temp\data.txt")
End If
linereader = Split(objectreader.ReadLine, ",")
If String.IsNullOrEmpty(linereader(0)) Then
objectreader.Close()
objectreader = Nothing
Else
txtSpelling1.Text = linereader(0) 'Word
txtSpelling2.Text = linereader(1) 'Hint
End If
End Sub
End Class
But in your case, I would probably just use the File.ReadAllLines Method
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim result As String() = File.ReadAllLines("C:\Temp\data.txt")
For x = 0 To UBound(result)
Dim c As Control = Controls.Find("txtSpelling" + (x + 1).ToString, True)(0)
If Not IsNothing(c) Then
c.Text = Split(result(x), ",")(0)
End If
Next
End Sub

Object reference not set to an instance of an object in Visual Studio 2010

I am trying to make a program that takes a text from a file and writes it into a label in visual studios 10. I want to be able to click buttons on the exe to make it go from the previous line to the next line and vise versa. I am storing the text into an array and then making the label equal the text on the given part of the array. I am receiving the error "Object reference not set to an instance of an object." Can anyone help ? thanks. here is part of my code my code:
Private Sub BrowseButton_Click(sender As System.Object, e As System.EventArgs) Handles BrowseButton.Click
Dim UserInput As DialogResult = Browser.ShowDialog()
If UserInput = Windows.Forms.DialogResult.Cancel Then
Return
End If
FileOpen(1, Browser.FileName, OpenMode.Input)
Do While Not EOF(1)
Input(1, InternalTextFile(Index))
Index += 1
Loop
FileClose(1)
Output1Text.Text = InternalTextFile(Index)
Output2Text.Text = InternalTextFile(Index + 1)
End Sub
The error arises On the line Input(1, InternalTextFile(Index))
Without seeing more code it's hard to tell, but if the error is on Input(1, InternalTextFile(Index)), its likely that the variable InternalTextFile was never assigned a value. Something like this maybe?
Dim InternalTextFile As New List(of String)
Dim reader As StreamReader = New StreamReader(Browser.FileName)
Try
Do
InternalTextFile.Add(reader.ReadLine)
Loop Until reader.Peek = -1
Finally
reader.Close()
End Try
It looks like maybe you want something like this:
Private Sub BrowseButton_Click(sender As System.Object, e As System.EventArgs) Handles BrowseButton.Click
If Browser.ShowDialog() = Windows.Forms.DialogResult.Cancel Then Exit Sub
Dim InternalTextFile() As String = File.ReadAllLines(Browser.FileName)
Output1Text.Text = InternalTextFile(InternalTextFile.Length - 2)
Output2Text.Text = InternalTextFile(InternalTextFile.Length - 1)
End Sub

Extracting specific lines from one text file to other text file

I want to extract some specific lines from a text file to other text file. i am using the following code
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Tr As IO.TextReader = System.IO.File.OpenText("C:\Assignment.txt")
For c As Integer = 1 To 10
If c = 7 Then
Dim MyFileLine As String = Split(Tr.ReadToEnd(), vbCrLf)(c) & vbCrLf
Tr.Close()
Dim TW As System.IO.TextWriter
'Create a Text file and load it into the TextWriter
TW = System.IO.File.CreateText("C:\Assignment1.txt")
TW.WriteLine(MyFileLine)
'Flush the text to the file
TW.Flush()
'Close the File
TW.Close()
End If
Next c
End Sub
End Class
But this code extract only the line no 7 where i want to extract the 8th,9th,10th,14th,15th,16th, lines also . Please guide me the right solution. Thank u in advance.
There seems to be several issues here. I will correct them and then explain below:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim currentLine As String
Dim lineCounter As Integer = 1
Dim lineNumbersRequired As List(Of Integer) = New List(Of Integer)
lineNumbersRequired.Add(7)
lineNumbersRequired.Add(8)
lineNumbersRequired.Add(9)
lineNumbersRequired.Add(10)
lineNumbersRequired.Add(14)
lineNumbersRequired.Add(15)
lineNumbersRequired.Add(16)
Dim TW As System.IO.TextWriter
'Create a Text file and load it into the TextWriter
TW = System.IO.File.CreateText("C:\Assignment1.txt")
Using Tr As IO.TextReader = New IO.StreamReader("C:\Assignment.txt")
While Not Tr.EndOfStream
If lineNumbersRequired.Contains(lineCounter) Then
Dim MyFileLine As String = Split(currentLine, vbCrLf)(c) & vbCrLf
TW.WriteLine(MyFileLine)
End If
lineCounter = lineCounter + 1
End While
End Using
TW.Flush()
'Close the File
TW.Close()
End Sub
End Class
NOTE: Code not tested, but should be pretty close if you do get a few compile errors!
Ok then, just a quick rundown of what I did here:
Changed the For Loop into a while because you had the for loop running from 1 To 10, so even if it worked, then you would have never read past the 10th line in your file. So I have changed it to a while loop that will end when the TextReader has read all lines in the file. Also the current line read from the file has been added to a new variable called currentLine.
The new currentLine variable is now used to populate the lines of your writing file.
I have added a list of Integers that will hold the line numbers you want to keep, then within the while loop I have a counter that counts each line as it is processed and if this counter is inside the list of line numbers you want to save into your output file, then it will output the current line.
Let me know how you get on, and if you need more of an explanation on any of it then please ask.