从第2行到第4行从文本文件中获取数据

时间:2018-02-28 23:04:17

标签: vb.net

我有一个需要从第2到第4行获取数据的项目

示例数据

1Type
2DELL LAPTOP
3HP   LAPTOP
4ASUS LAPTOP
1ACCESSORIES
2DELL  MOUSE
3HP    MOUSE
4ASUS  MOUSE

我的代码

Dim myStreamReader As New IO.StreamReader("C:\tmp\Parts.txt")
Dim myStreamWriter As New IO.StreamWriter("C:\tmp\GetData.txt")
Dim getdata As String
Dim nLineCtr As Integer
Dim strline As String = objStreamReader.ReadLine()

While Not strline Is Nothing
    nLineCtr = nLineCtr + 1
    strline = objStreamReader.ReadLine
    If nLineCtr = 2 Or nLineCtr = 3 Or nLineCtr = 4 Then
        getdata = Mid(strline, 2, 11)
        myStreamWriter.WriteLine(getdata)
    End If
End While

myStreamWriter.Close()
myStreamWriter.Dispose()
myStreamWriter = Nothing
myStreamReader.Close()
myStreamReader.Dispose()
myStreamReader = Nothing

我得到的结果是

4ASUS LAPTOP
4ASUS  MOUSE

但我要求的结果是:

2DELL LAPTOP
3HP   LAPTOP
4ASUS LAPTOP
2DELL  MOUSE
3HP    MOUSE
4ASUS  MOUSE

如何更改我的代码以获得我需要的结果?

3 个答案:

答案 0 :(得分:0)

在我的手机上,所以我会说得很简单:

无需流式传输。只需使用System.IO

Dim lines() As String = file.ReadAllLines
Dim output As String

For Each line In lines
    Dim index As Integer = Int32.TryParse(line(0))
     If (index > 1 And index < 5) Then
         Output += line & vbNewLine
     End If
Next

然后剥去最后一个新行。

答案 1 :(得分:0)

安德鲁,我把所有东西放在一个列表中,然后设置为跳过每4行。只要模式保持不变,这应适用于任何大小的文件。

Sub Andrew()
        Dim lstData As List(Of String) = File.ReadAllLines("C:\MyFolder\Charles.txt").ToList
        Dim lstSelectedData As New List(Of String)
        Dim nLineCtr As Integer = 1
        Dim strLine As String = ""
        Dim SkipLine As Integer = 0
        For i = 0 To lstData.Count - 1
            If SkipLine <> i Then
                lstSelectedData.Add(lstData(i))
            Else
                SkipLine += 4
            End If
        Next
        For Each s As String In lstSelectedData
            Debug.Print(s)
        Next
End Sub

答案 2 :(得分:-1)

使用子字符串。

While Not strline Is Nothing
nLineCtr = nLineCtr + 1
strline = objStreamReader.ReadLine
If nLineCtr = 2 Or nLineCtr = 3 Or nLineCtr = 4 Then

    getdata = strline.Substring(0, 1)
    myStreamWriter.WriteLine(getdata)

    End If
End While