如何使用 vb.net 更新 CSV 文件以不插入新项目

How to Update CSV file not to Insert new Items using vb.net

我想更新我试过的 CSV 文件行,但我只找到添加新行的追加。因为我需要更新行而不是插入新行。

这是我的 csv 文件中的数据

EnjoyBaseHid=hid://002AB1E3,MinID=1,MaxID=900 EnjoyBaseHid=hid://005AC1D4,MinID=1,MaxID=600

我要根据EnjoyBaseHid更新

While Not sr.EndOfStream
                            Dim line = sr.ReadLine()
                            Dim values() As String = line.Split(",")
                            If values(0).Equals("EnjoyBaseHid=" & portAddress) Then
                                Nobasefound = False
                                line = line.Replace(values(1), "MinID=" & minID)
                                line = line.Replace(values(2), "MaxID=" & maxID)
                                sr.Close()
                                Dim strWrite As New IO.StreamWriter(ExportListPathString, False)
                                strWrite.WriteLine(line)
                                strWrite.Close()
                                Exit While
                            End If
End While

这会覆盖所有文件,结果是

EnjoyBaseHid=hid://005AC1D4,MinID=1,MaxID=1000

当我更改以下行时

Dim strWrite As New IO.StreamWriter(ExportListPathString, False)

对此

Dim strWrite As New IO.StreamWriter(ExportListPathString, True)

它追加新行,结果如下

EnjoyBaseHid=hid://002AB1E3,MinID=1,MaxID=900
EnjoyBaseHid=hid://005AC1D4,MinID=1,MaxID=600
EnjoyBaseHid=hid://005AC1D4,MinID=1,MaxID=1000

但我需要这个

EnjoyBaseHid=hid://002AB1E3,MinID=1,MaxID=900 EnjoyBaseHid=hid://005AC1D4,MinID=1,MaxID=1000

这是我的想法。

Private Sub fileHandler(sourceFile As String, portAddress As String, newMin As String, newMax As String)

    Dim tempOutFileName As String = String.Concat(sourceFile, "_tmp")
    Dim oldFileName As String = String.Concat(sourceFile, "_old")

    'clear away temp file
    If File.Exists(tempOutFileName) Then
        File.Delete(tempOutFileName)
    End If

    'clear away old file
    If File.Exists(oldFileName) Then
        File.Delete(oldFileName)
    End If

    'open writer for new temp file
    Using sw As StreamWriter = New StreamWriter(tempOutFileName, True)
        'open reader for source file
        Using sr As StreamReader = New StreamReader(sourceFile)
            Do While sr.Peek <> -1
                Dim line As String = sr.ReadLine
                'check if the line read is the one you want to change
                If line.Contains(portAddress) Then
                    'write your NEW line
                    sw.WriteLine(String.Concat(portAddress, "-", newMin, "-", newMax))
                Else
                    'write the existing line without changes
                    sw.WriteLine(line)
                End If
            Loop
            sr.Close()
        End Using
        sw.Close()
    End Using

    'backup source to old
    File.Move(sourceFile, oldFileName)
    'move temp to source
    File.Move(tempOutFileName, sourceFile)

End Sub