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

时间:2015-10-01 12:35:05

标签: vb.net streamreader streamwriter

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

这是我的csv文件中的数据

EnjoyBaseHid =藏:// 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 =藏:// 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 =藏:// 002AB1E3,MinID = 1,MaxID = 900 EnjoyBaseHid = HID:// 005AC1D4,MinID = 1,MaxID = 1000

1 个答案:

答案 0 :(得分:0)

这是我想到的想法。

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