如何加载.txt文件并在每行上分隔符后擦除

时间:2016-11-18 15:04:32

标签: vb.net

我正在加载.txt文件,该文件包含firstName:lastName格式的大约一千个名称。我现在只需要我正在做的第一个名字。如何删除列表框中显示的整个列表,并仅显示名字?

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

2 个答案:

答案 0 :(得分:1)

您可以将每一行拆分为一个子数组,并将第一个元素返回到一个新数组

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

答案 1 :(得分:1)

使用String.Split在分隔符处分开每一行并使用返回的第一部分:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"n2/51OSHlNP+1E7qnLku/gXtCjUk/MfMxwsrNpUirR2IbQddOzP1/OClL50ClCPvDNIowvdsqpVNmer37Egp4w==", 
 "scenario"=>{"title"=>"title #8", "abstract"=>"abstract", "roles"=>{"name"=>"aaa"}}}

我使用ListBox1.Items.AddRange( System.IO.File.ReadLines(TextBox2.Text).Select( Function(x) x.Split(":"c)(0) ).ToArray() ) 代替ReadLines,因为它可能会更高效,但看起来ReadAllLines仍然需要一个数组,因此AddRange调用。

但是,它确实取决于您在列表中有项目后要执行的操作。最好为全名创建一个类,然后将文件读入这些文件的列表中,然后使用ToArrayDataSource进行绑定。