在文件中读取未知数量的行

时间:2017-11-30 20:41:05

标签: vb.net file file-io

我有大约20个文件,每个文件都有一个简短的描述,从第7行开始,然后转到文件的第3行到最后一行。 例如,一个文件的描述从第7行开始,到第10行结束,但该文件总共有13行。

如何导入JUST描述,例如第7-10行? 这是我到目前为止的示例代码。

Public Class Form1

    Dim MyDir As String = "..\GoodFils\"
    Dim MyFiles() As String = IO.Directory.GetFiles(MyDir)
    Dim Count As Integer = 0

    Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
        Return lines(lineNumber - 1)
    End Function

    Private Sub btnDo_Click(sender As Object, e As EventArgs) Handles btnDo.Click
        Dim reader As New System.IO.StreamReader(MyDir & "gucci.hcs")
        Dim allLines As List(Of String) = New List(Of String)
        Dim i As Integer
        Dim strTemp As String

        Do Until reader.EndOfStream = True
            allLines.Add(reader.ReadLine())
        Loop

        lblName.Text = ReadLine(2, allLines)
        lblPrice.Text = ReadLine(5, allLines)
        lblDesc.Text = EOF(1) - 3

        reader.Close()
        FileOpen(1, MyDir & "gucci.hcs", OpenMode.Input) 'May be able to use MyDir & lblName & ".hcs"

        For i = 7 To reader.EndOfStream
            Input(1, strTemp)
        Next

        lblDesc.Text += i
        FileClose(1)
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

您可以使用IO.File.ReadAllLines将每个文件的内容加载到数组中,然后您可以使用LINQ跳过跳转到第7行,然后转到第3行到最后一行。

这是一个简单的例子:

'Create a collection to store all of the file's descriptions
Dim descriptions As New List(Of String)

'Placeholder variable for the upcoming iteration
Dim lines() As String

'Iterate through each file
For Each file As IO.FileInfo In New IO.DirectoryInfo("GoodFils").GetFiles("*.txt")
    'Read the file
    lines = IO.File.ReadAllLines(file.FullName)

    'Get only lines 7 to n-3
    descriptions.Add(String.Join(Environment.NewLine, lines.Skip(6).Take(lines.Count - 10).ToArray()))
Next

小提琴:Live Demo

相关问题