如何使用Vb.Net中的streamwriter从字符串变量创建csv文件?

时间:2014-09-23 12:19:33

标签: vb.net csv

我正在使用.Net 4.0在VS 2012,Vb.Net上工作。

使用Streamwriter或FileStream,我试图创建一个Temp csv,它将位于c:\ windows \ temp文件夹中。 .csv文件的值将从字符串变量填充。

字符串变量中的示例值看起来像..

1,2,3,411,345
2,3,4,55,678
5,6,7,8,9999

如何从字符串变量中编写.csv文件?

Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead("D:\CSV\Test.csv"))
Dim listA As New List(Of String)()
Dim listB As New List(Of String)()
Dim s As String = ""
While Not reader.EndOfStream
    Dim line As String = reader.ReadLine()
    Dim values As String() = line.Split(";"c)
    listA.Add(values(0))
    s = s + line + Chr(10)
End While

1 个答案:

答案 0 :(得分:5)

使用Streamwriter(sw是变量声明)。我能写.csv文件。

 Public Sub Test()
        Try

            Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead("D:\CSV\Test.csv"))
            Dim listA As New List(Of String)()


            If File.Exists("d:\CSV\TestOut.csv") Then
                File.Delete("d:\CSV\TestOut.csv")
            End If

            Dim sw As New StreamWriter("d:\CSV\TestOut.csv")
            Dim s As String = String.Empty

            While reader.Peek() >= 0
                Dim line As String = reader.ReadLine()
                Dim values As String() = line.Split(";"c)
                listA.Add(values(0))
                s = s + line + Chr(10)
            End While
            reader.Close()
            sw.Write(s)
            sw.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub