如何在VB.Net中手动向DataReader添加值

时间:2011-06-10 11:41:32

标签: .net vb.net

我将sample.csv文件的内容复制到new.csv文件中。但我需要在new.csv文件中添加其他列,该文件对旧文件中存在的每一行保留默认值“是”。这是我写的代码。

  Dim ioFile As New System.IO.StreamReader("C:\sample.csv")      
  Dim ioLine As String
  Dim ioLines As String      
  ioLine = ioFile.ReadLine     
  ioLines = "ID","Name","Number","Amount","Copied"
  ioLines &= vbCrLf & ioLine 
  While Not ioLine = ""         
    ioLine = ioFile.ReadLine         
    ioLines = ioLines & vbCrLf & ioLine      
  End While     
  Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")     
  ioWriter.WriteLine(ioLines)     
  ioFile.Close()     
  ioWriter.Close()

前四列ID,名称,编号,金额存在于sample.csv中。我正在添加其他列Copied,每行应为“是”。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

我只是将值附加到现有循环中,如:

  While Not ioLine = ""         
    ioLine = ioFile.ReadLine
    if ioLine <> "" then ioLine &= ",Yes"
    ioLines = ioLines & vbCrLf & ioLine      
  End While     

答案 1 :(得分:2)

试试这个:

Private Sub Test()
    Dim ioFile As New System.IO.StreamReader("C:\sample.csv")

    Dim content As String
    content = ioFile.ReadToEnd
    ioFile.Close()

    Dim ContentArray() As String
    ContentArray = Split(content, vbCrLf, -1, CompareMethod.Binary)

    Dim current As String
    Dim sb As New System.Text.StringBuilder
    sb.Append("ID,Name,Number,Amount,Copied")

    For Each current In ContentArray
        sb.Append(vbCrLf & current & ",Yes")
    Next

    Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
    ioWriter.Write(sb.ToString)

    ioWriter.Close()

End Sub

答案 2 :(得分:0)

只需将值附加到循环中的行字符串即可。

While Not ioLine = ""         
    ioLine = ioFile.ReadLine         
    ioLine &= ",Yes"  
    ioLines = ioLines & vbCrLf & ioLine      
End While 

编辑:这应该考虑您的循环条件。

  While Not ioLine = ""         
    ioLine = ioFile.ReadLine
    if ioLine <> "" then 
      ioLine &= ",Yes"
      ioLines = ioLines & vbCrLf & ioLine   
    end if   
  End While   

感谢您的帮助,@ D ..