Reading from text file to ListBox - vb.net

I am having a bit of trouble reading data from a text file. This almost works, however data in separate lines in the text file is combined to one long line in the ListBox. How else to do it?
Private Sub frmOpretrskAar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
LBmuligeFirmaer.Items.Add(objReader.ReadToEnd)
objReader.Close()
End Sub

Use the ListBox.Items.AddRange method to add an array, in this case it would be an array that represents the lines of the text file. You can get the lines by using IO.File.ReadAllLines method. Here is a quick example:
LBmuligeFirmaer.Items.AddRange(IO.File.ReadAllLines("c:\users\claus\onedrive\SLERP\fmr.txt"))

Its very simple -
List<string> _list = File.ReadAllLines(fileName).ToList();
See the below image -

You can use array.
Try this code:
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
Dim AllLines() As String = System.IO.File.ReadAllLines(FILE_NAME)
For i As Integer = 0 To AllLines.Count - 1
LBmuligeFirmaer.Items.Add(AllLines(i))
Next

I can't test this in my IDE currently so tell me if something doesn't work right but I have used something similar:
Imports System.IO
Imports System.Windows.Forms
'assigning a string value to the file's location
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
'clearing the listbox
LBmuligeFirmaer.items.clear
'declaring a filereader
Dim fileReader As System.IO.StreamReader
fileReader =
'obtaining file location from string to the stringreader
My.Computer.FileSystem.OpenTextFileReader(FILE_NAME)
Dim stringReader As String
'reading first line
stringReader = fileReader.ReadLine()
'adding line to the listbox
LBmuligeFirmaer.items.add(stringreader)
'reading second line
stringReader = fileReader.ReadLine()
'adding line to listbox
LBmuligeFirmaer.items.add(stringreader)
'and so on...

Related

VB.Net Search for text and replace with file content

This is a follow on question to a post I made. Append one file into another file
I need to search the master document for entities "&CH1.sgm" to "&CH33.sgm",
mark where they are in the master document and replace the entity call with the matching file "Chapter1.sgm" found in "fnFiles". I can change the file names and entities to anything if that will help.
My code copies the text of a file and appends it to the bottom of the master_document.sgm. But now I need it to be more intelligent. Search the Master document for entity markers, then replace that entity marker with that file contents match. The file number and entity number match up. e.g.(&CH1; and Bld1_Ch1.sgm)
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
Dim searchDir As String = txtSGMFile.Text 'Input field from form
Dim masterFile = "Bld1_Master_Document.sgm"
Dim existingFileMaster = Path.Combine(searchDir, masterFile)
'Read all lines of the Master Document
Dim strMasterDoc = File.ReadAllText(existingFileMaster) '// add each line as String Array.
'?search strMasterDoc for entities &Ch1.sgm
'?replace entity name "&Ch1.sgm" with content of file "Bld1_Ch1.sgm" this content if found below
'? do I use a book mark? Replace function?
'Get all the sgm files in the directory specified
Dim fndFiles = Directory.GetFiles(searchDir, "*.sgm")
'Set up the regular expression you will make as the condition for the file
Dim rx = New Regex(".*_Ch\d\.sgm")
Dim ch1 = New Regex(".*_Ch[1]\.sgm")
'Use path.combine for concatenatin directory together
'Loop through each file found by the REGEX
For Each fileNo In fndFiles
If rx.IsMatch(fileNo) Then
If ch1.IsMatch(fileNo) Then
Dim result = Path.GetFileName(fileNo)
'Use path.combine for concatenatin directory together
Dim fileToCopy = Path.Combine(searchDir, result)
'This is the file we want to copy into MasterBuild but at specific location.
'match &ch1.sgm inside strMasterDoc
Dim fileContent = File.ReadAllText(fileToCopy)
'Search master file for entity match then append all content of fileContent
File.AppendAllText(existingFileMaster, fileContent)
MessageBox.Show("File Copied")
End If
End If
Next
Close()
End Sub
If I understand correctly (big if), you want to replace the the text of the abbreviated chapter name in the master file with the contents of the file it refers to at the spot where the abbreviation is found.
I made a class to handle the details.
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
'Add a FolderBrowseDialog to your form designer
FolderBrowserDialog1.ShowDialog()
Dim searchDir As String = FolderBrowserDialog1.SelectedPath
Dim existingFileMaster = Path.Combine(searchDir, "Bld1_Master_Document.sgm")
Dim lstFileChanges = CreateList(searchDir)
'The following method does NOT return an array of lines
Dim strMasterDoc = File.ReadAllText(existingFileMaster)
For Each fc In lstFileChanges
strMasterDoc = strMasterDoc.Replace(fc.OldString, fc.NewString)
Next
File.WriteAllText(existingFileMaster, strMasterDoc)
End Sub
Private Function CreateList(selectedPath As String) As List(Of FileChanges)
Dim lstFC As New List(Of FileChanges)
For i = 1 To lstFC.Count
Dim fc As New FileChanges
fc.OldString = $"&CH{i}.sgm"
fc.FileName = $"Chapter{i}.sgm"
fc.NewString = File.ReadAllText(Path.Combine(selectedPath, fc.FileName))
lstFC.Add(fc)
Next
Return lstFC
End Function
Public Class FileChanges
Public Property OldString As String '&CH1.sgm
Public Property FileName As String 'Chapter1.sgm
Public Property NewString As String 'Contents of Chapter1.sgm, the string to insert
End Class
Testing .Replace
Dim s As String = "The quick brown fox jumped over the lazy dogs."
s = s.Replace("fox", "foxes")
MessageBox.Show(s)

Delete entire line if it contains specific word

I also want to display the line containing the word. I want to open an external .txt file and delete any line if it contains a specific string. I have a search and replace at the moment for one word but want the entire line to be removed from the file. Thanks
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myStreamReaderL1 As System.IO.StreamReader
Dim myStream As System.IO.StreamWriter
Dim myStr As String
myStreamReaderL1 = System.IO.File.OpenText("C:\Users\f1r1a\Desktop\memes.txt")
myStr = myStreamReaderL1.ReadToEnd()
myStreamReaderL1.Close()
myStr = myStr.Substring("fraser", 6)
'Save myStr
myStream = System.IO.File.CreateText("C:\Users\f1r1a\Desktop\memes.txt")
myStream.WriteLine(myStr)
myStream.Close()
End Sub
Well you can do all of that code in two lines
Dim result = File.ReadLines("C:\Users\f1r1a\Desktop\memes.txt").
Where(Function(x) Not x.Contains("fraser"))
File.WriteAllLines("C:\Users\f1r1a\Desktop\memes.txt", result.ToArray)
The IEnumerable extension Where receives, line by line, the sequence produced by File.ReadLines. Each line is processed by Where applying the Contains method and if the line doesn't contains the word searched then it is passed as output to the result variable. In turn the result variable is passed as an array to the WriteAllLines method.
You can get both at once:
Dim file = "C:\Users\f1r1a\Desktop\memes.txt"
Dim lookup = File.ReadLines(file).ToLookup(Function(l) l.Contains("fraser"))
textBoxRemoved.Text = String.Join("|", lookup(True))
File.WriteAllLines(file, lookup(False))

partial .txt file to datagridview vb.net

i have a user interface form that let's you upload a text file to a datagridview as follows
Sub Datagrid()
Dim sw = System.Diagnostics.Stopwatch.StartNew()
Using stream As System.IO.FileStream = System.IO.File.OpenRead(TextBox1.Text)
Using reader As New System.IO.StreamReader(stream)
Dim line As String = reader.ReadLine()
While (line IsNot Nothing)
Dim columns = line.Split(";")
line = reader.ReadLine()
Dim index = Me.DataGridView1.Rows.Add()
Me.DataGridView1.Rows(index).SetValues(columns)
End While
End Using
End Using
sw.Stop()
End Sub
Well, now my problem is that i don't want to put the full txt file in that datagridview, just from line N.
Is it possible to do that? Like creating a querytabel and selecting a fixed value?
p.e., in line 5 there's always the text "Values:" . Can i select all the lines after that to put in the datagridview? i googled everywhere but found nothing. and there's no "sample" code to give me a start . thank you all !
Dim n As Integer = 5
Dim lines As IEnumerable(Of String) = IO.File.ReadAllLines("textbox1.text").Skip(n)
'Gets every line after a certain line count
'Create a new datatable and add some columns
Dim dt As New DataTable
dt.Columns.AddRange((From columnIndex As Integer In Enumerable.Range(1, lines.First.Split(";"c).Count) Select New DataColumn("Column" & columnIndex.ToString())).ToArray())
'Add each line as a row to the datatable
For Each line As String In lines
dt.Rows.Add(line.Split(";"c))
Next
'Set the datasource of the datagridview
MyDataGridView.DataSource = dt

Variable has already been used before and assigned a value

I' am making a bot for my assignment which uses proxy to browse websites. I have field called "Browse" which lets me browse for the proxy file and reads into an array and shows the total number of proxy from the counter. I' am stuck here in the following. The following are the code that am currently using. Please help
Variable proxyArray has already been used before and assigned a value. A null
reference exception could result at runtime.
Code
Private Sub browserProxy_Click(sender As Object, e As EventArgs) Handles browserProxy.Click
Dim myStream As Stream = Nothing
Dim selectedFile As String
Dim openFileDialog1 As New OpenFileDialog()
Dim proxyArray() As String
Dim totalProxy As Integer
openFileDialog1.InitialDirectory = "C:\"
openFileDialog1.Filter = "Text File (*.txt)|*.txt"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = False
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
selectedFile = String.Format(openFileDialog1.FileName)
Dim objreader As New System.IO.StreamReader(selectedFile)
i = 0
Do While Not objreader.EndOfStream
proxyArray(i) = objreader.ReadLine
i += 1
Loop
totalProxy = i
objreader.Close()
End If
End Sub
This pops up during runtime.
The compiler is right, you have declared the variable proxyArray but you never initialize it. This is an initialized array with 10 strings that are Nothing
:
Dim proxyArray(9) As String
But since the number of items is unknown you should use a List(Of String) anyway. It is resizable whereas an array has a fixed size.
Dim proxList As New List(Of String)
'...'
proxList.Add(objreader.ReadLine)
If you need an array you can use proxList.ToArray() at the end.
Either use a List(Of String), or ReDim Preserve proxyArray(i + 1) each time.

Splitting a CSV Visual basic

I have a string like
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
in a file
in two separate lines. I am reading it from the textbox. I have to output ab563372363_C/R and ab563372356_C/R in a text box. I am trying to use the split function for that but its not working..
Dim splitString as Array
results = "test.txt"
Dim FileText As String = IO.File.ReadAllText(results) 'reads the above contents from file
splitString = Split(FileText, ",", 14)
TextBox2.text = splitString(1) & splitString(13)
for the above code, it just prints the whole thing.. What's wrong?
Try this
Private Function GetRequiredText() As List(Of String)
Dim requiredStringList As New List(Of String)
Dim file = "test.txt"
If FileIO.FileSystem.FileExists(file) Then
Dim reader As System.IO.StreamReader = System.IO.File.OpenText(file)
Dim line As String = reader.ReadLine()
While line IsNot Nothing
requiredStringList.Add(line.Split(",")(1))
line = reader.ReadLine()
End While
reader.Close()
reader.Dispose()
End If
Return requiredStringList
End Function
This will read the file line by line and add the item you require to a list of strings which will be returned by the function.
Returning a List(Of String) may be overkill, but it's quite simple to illustrate and to work with.
You can then iterate through the list and do what you need with the contents of the list.
Comments welcome!!
Also this might work...
Dim query = From lines In System.IO.File.ReadAllLines(file) _
Select lines.Split(",")(1)
this will return an IEnumerable(Of String)
Enjoy
First
Since you are reading the whole text, your FileText would be ending like this:
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132,460
\r\n
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
So when you are referencing to your splitStringwith those indexes (1, 13) your result might probably be wrong.
Second
Try to specify what kind of type your array is, Dim splitString as Array should be Dim splitString As String()
Third
Make your code more readable/maintainable and easy to edit (not only for you, but others)
The Code
Private const FirstIndex = 1
Private const SecondIndex = 12
Sub Main
Dim myDelimiter As Char
Dim myString As String
Dim mySplit As String()
Dim myResult1 As String
Dim myResult2 As String
myDelimiter = ","
myString += "Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460"
myString += "Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455"
mySplit = myString.Split(myDelimiter)
myResult1 = mySplit(FirstIndex)
myResult2 = mySplit(SecondIndex)
Console.WriteLine(myResult1)
Console.WriteLine(myResult2)
End Sub