【问题标题】:Read lines from a text file in VB.NET从 VB.NET 中的文本文件中读取行
【发布时间】:2014-01-29 02:09:39
【问题描述】:

我有一个文本文件格式:

  *******************************************************************************
    *                              Mitecs Test Plan                               *
    *******************************************************************************

    [PRODUCTN]
    FQA=3F.4.W0,41,1
    RSC=3F.5.W4,36,1
    CFG=3F.9.2J,234,1

    [MASTERREV]
    MTP=3F.R.WM

    [FQA 13]
    FQA=3F.4.W0,41,1
    CFG=3F.9.2J,263,1

    [FQA 14]
    FQA=3F.4.W0,160,1
    CFG=3F.9.2J,315,1

我想阅读文本并将其显示在列表框中,如下所示:

[PRODUCTN]
[MASTERREV]
[FQA 13]
[FQA 14]

从上图中,当我在列表框 1 中选择 [FQA 14] 项并单击交换按钮时,它应该在列表框 2 中以以下格式显示为

Code    Name    Version
160     FQA      3F.4.W0
315     CFG      3F.9.2J

【问题讨论】:

  • 它看起来像一个INI文件,你应该可以使用GetPrivateProfileString访问Pinvoke.Net
  • @Plutonix INI 文件对 cme​​ts 使用哈希符号 # 或分号 ;,但 OP 的示例使用星号 *。他的文件的 Win32 INI 函数可能会失败。
  • @Dai 实际上非常灵活,阅读起来应该不会有任何问题。

标签: vb.net text programmers-notepad


【解决方案1】:

一种选择是使用一个类来保存每个条目并覆盖 ToString 函数以返回标题。现在您可以将每个条目直接添加到 listbox1 中,它将显示代表该项目的标题。由于每个列表框项目实际上都是一个对象,因此您可以将所选项目转换为您的条目类并从对象中读取数据。这是一种方法:

Public Class Entry
    Public Property Title As String = ""
    Public Property Data As New List(Of String)
    Public Overrides Function ToString() As String
        Return Title
    End Function
End Class

Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim sr As New StreamReader("textfile1.txt")
    Do Until (sr.EndOfStream)
        Dim line As String = sr.ReadLine.Trim
        If line.StartsWith("[") Then
            Dim newentry As New Entry
            newentry.Title = line
            Do Until (line = "" OrElse sr.EndOfStream)
                line = sr.ReadLine.Trim
                If Not line = "" Then
                    newentry.Data.Add(line)
                End If
            Loop
            ListBox1.Items.Add(newentry)
        End If
    Loop
End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    Dim selectedentry As Entry = DirectCast(DirectCast(sender, ListBox).SelectedItem, Entry)
    ListBox2.Items.Clear()
    For Each datum In selectedentry.Data
        Dim line As String() = datum.Split("=,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
        If line.Count > 2 Then
            ListBox2.Items.Add(line(2) + vbTab + line(0) + vbTab + line(1))
        Else
            ListBox2.Items.Add("   " + vbTab + line(0) + vbTab + line(1))
        End If
    Next
End Sub

【讨论】:

  • 入口类抛出错误
  • 什么样的错误?代码经过测试,可与您提供的示例文件一起使用。
猜你喜欢
  • 2010-12-26
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多