使用VB.net动态编辑CSV文件的内容

时间:2016-11-26 08:58:00

标签: vb.net csv

我有这段代码

  Dim fileReader As System.IO.StreamReader
        fileReader =
        My.Computer.FileSystem.OpenTextFileReader("Filepath")

        Dim stringReader As String
        'read csv file from first to last line
        While fileReader.ReadLine <> ""
            'get data of line
            stringReader = fileReader.ReadLine()
            'check the number of commas in the line
            Dim meh As String() = stringReader.Split(",")
            If meh.Length > 14 Then

                My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)

            ElseIf meh.Length < 14 Then

                My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)

            ElseIf meh.Length = 14 Then

                MsgBox("This line of the file has " & stringReader & meh.Length & "commas")

            End If

        End While
        End
    End Sub

为了解释,上面的代码将检查CSV文件的EACH行以检查天气内容有14个逗号(')。然后,如果该行有更多逗号,代码将减少到14,如果没有,它将写入逗号,使其等于14.上述条件尚未创建,因此代码仅用于测试。我读了一些关于WriteAllText的内容,这段代码给了我错误:

The process cannot access the file 'filepath' because it is being used by another process.

我认为,这意味着我无法编辑CSV文件,因为我目前正在使用其数据。

我的问题是,即使我检查其内容,我怎么能编辑CSV文件的内容?

请忽略此代码

My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)

因为我使用此代码进行测试,如果我能设法将其写入CSV文件。

我感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

如果您的CSV不是太大,您可以在内存中阅读它并使用它。完成后,您可以在磁盘上再次写入。

    'Declare 2 List (or you can work directly with one)
    Dim ListLines As New List(Of String)
    Dim ListLinesNEW As New List(Of String)

    'Read the file
    Using MyCSVread As New IO.FileStream("C:\MyCSV.csv", IO.FileMode.Open, IO.FileAccess.ReadWrite)

      'Read all the lines and put it in a list of T (string)  
      Using sReader As IO.StreamReader = New IO.StreamReader(MyCSVread)
            Do While sReader.Peek >= 0
                ListLines.Add(sReader.ReadLine)
            Loop
        End Using
    End Using

    'Your code for work with the line. Here you can write the new lines in the NEW list of string or work directly in the first
    For L As Integer = 0 To ListLines.Count - 1
        Dim meh As String() = ListLines(L).Split(",")
        If meh.Length > 14 Then
            'your code ...
        ElseIf meh.Length < 14 Then
            'your code ...
        ElseIf meh.Length = 14 Then
            MessageBox.Show("The line " & (ListLines(L) + 1) & " of the file has " & meh.Length & "commas", "MyApp", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    Next

    'Open again the file for write
    Using MyCSVwrite As New IO.FileStream("C:\MyCSV.csv", IO.FileMode.Open, IO.FileAccess.ReadWrite)

        'Write back the file with the new lines
        Using sWriter As IO.StreamWriter = New IO.StreamWriter(MyCSVwrite)
            For Each sLine In ListLinesNEW.ToArray
                sWriter.WriteLine(sLine)
            Next
        End Using
    End Using

&#34;使用&#34;自动关闭文件流或流读取器/写入或您使用的内容。那么你就不会有&#34;文件已经在使用&#34;。

希望得到这个帮助。