Kane31 Kane31 - 17 days ago 6
Vb.net Question

How to load a .txt file and erase after delimiter on each line

I am loading a .txt file that contains around a thousand names in a firstName:lastName format. I only need the firstnames for what I'm doing right now. How can I strip the entire list, which is displayed in a listbox, and display first names only?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:temp"
OpenFileDialog1.ShowDialog()
End Sub

Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox2.Text = OpenFileDialog1.FileName.ToString()
ListBox1.Items.AddRange(System.IO.File.ReadAllLines(TextBox2.Text))
End Sub

Answer

You can split each line into a sub-array, and return the first element into a new array

Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
    Dim strm As System.IO.Stream
    strm = OpenFileDialog1.OpenFile()
    TextBox2.Text = OpenFileDialog1.FileName.ToString()
    ListBox1.Items.AddRange(
        System.IO.File.ReadAllLines(TextBox2.Text).
        Select(Function(l) l.Split(":"c).FirstOrDefault()).
        ToArray())
End Sub
Comments