you could do it something like this Read the data with a data reader one record at a time. then create a string that represents each field in the record separated by a comma then just write it to your file
Private Sub CreateFile() Dim conn As SqlConnection = New SqlConnection(connString) conn.Open() Dim sql As String = "SELECT * FROM MyTable;" Dim cmd As SqlCommand = New SqlCommand(sql, conn) Dim dr As SqlDataReader = cmd.ExecuteReader() Dim s As Stream = File.Open("C:\MyCsv.csv", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read) Dim w As StreamWriter = New StreamWriter(s) While (dr.Read()) Dim s1 As String = "" Dim s2 As String = "" Dim s3 As String = "" If Not (dr(0) Is DBNull.Value) Then s1 = dr(0) End If If Not (dr(1) Is DBNull.Value) Then s2 = dr(1) End If If Not (dr(0) Is DBNull.Value) Then s3 = dr(2) End If Dim ss As String() = New String(2) {s1, s2, s3} WriteLine(w, ss) End While w.Close() dr.Close() conn.Close() End Sub
Private Sub WriteLine(ByVal w As StreamWriter, ByVal strings As String()) Dim sOut As String = "" For Each s As String In strings sOut = sOut + s + "," Next 'Remove the last comma Dim index As Integer = sOut.LastIndexOf(",") sOut = sOut.Remove(index, 1) w.WriteLine(sOut) End Sub |