Visual Basic 追加到文本文件中的特定点

Visual Basic Append to a specific point in a text file

我目前正在尝试使用逗号分隔符操作我们用来保留数据的文件中的一行。例如 -

121,1212, XJAY,Sean K,Kean S,AAAA-BBBB-AAAA-BBBB-AAAA
12456,987654,WYST,Steve Jobs,Bill Gates,CAAA-BBBB-AAAA-BBBB-AAAA

如果我假设最后一行始终是唯一代码,是否可以在文本文件中识别该行并将其附加到另一个字段?

之前的研究一直在通读 StreamReaderStreamWriter 的 API,并查看其他 Whosebug 问题,但是大多数问题似乎只关注附加到文件末尾,或者在不同的语言!

一如既往地感谢您的宝贵时间,如果有任何遗漏,请告诉我!

您无法以任何相当简单的方式操作文件中的一行。

没有处理文件中行的方法,因为文件不是基于行的。它们甚至不是基于字符的。将文件中的字节解码成字符,然后识别换行符,将字符拆分成行。

操作一行的最简单方法是将整个文件读入一个字符串数组,更改您想要更改的字符串,然后将整个字符串数组写入文件。

示例:

Dim fileName As String = "c:\data.txt"
Dim lines As String() = File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Length - 1
  Dim line As String = lines(i)
  If line.StartsWith("12456,") Then
    lines(i) = line & ",More data"
  End If
Next
File.WriteAllLines(fileName, lines)

如果您正在寻找一种使用 StreamReader 和 StreamWriter 解析每一行的方法:这里是:

            'You will need Imports System.IO
            Dim TheNewFile As String
            Dim MyLine As String
            Dim MyStream2 As New FileStream("C:\Your Directory\YourFile.txt", FileMode.Open)
            Dim MyReader As New StreamReader(MyStream2)
            Dim MySettings As New StringReader(MyReader.ReadToEnd)
            MyReader.BaseStream.Seek(0, SeekOrigin.Begin)
            MyReader.Close()
            MyStream2.Close()
            Try
                Do
                    MyLine = MySettings.ReadLine
                    'This if statement is an exit parameter. It can be if it contains or if 5 consecutive lines are nothing. It could be a number of things
                    If MyLine Is Nothing Then Exit Do
                    'This is the file you will write. You could do if MyLine = "Test" Then ........... append whatever and however you need to
                    TheNewFile = TheNewFile & MyLine & vbCrLf

                Loop
            Catch ex As Exception
                MsgBox(ex.ToString())
            End Try
            '-----------------Write The new file!!!----------------
            Dim MyStream3 As New FileStream("C:\Where you want to write New File\NewFileName.txt", FileMode.Create)
            Dim MyWriter3 As New StreamWriter(MyStream3)
            MyWriter3.Write(TheNewFile & "Test")
            MyWriter3.Close()
            MyStream3.Close()