Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a csv file from string variable using streamwriter in Vb.Net?

Tags:

csv

vb.net

I am working on VS 2012, Vb.Net using .Net 4.0.

Using Streamwriter or FileStream, I am trying to create a Temp csv which will be located in c:\windows\temp folder. Values for the .csv file will be populated from a string variable.

Sample values in the string variable will look like as..

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

How to write a .csv file from string variable ?

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
like image 223
goofyui Avatar asked Sep 23 '14 12:09

goofyui


1 Answers

Using Streamwriter ( sw is the variable declaration) . I am able to write .csv file.

 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
like image 189
goofyui Avatar answered Sep 29 '22 21:09

goofyui