VB.net code to convert a data reader to stringbuilder

Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 2089
The below code will do so

Public Shared Function ConvertDataReaderToStringBuilder(sqlConnectionString As String, storedprocedureName As String) As StringBuilder
Dim sb As New StringBuilder()
Using sqlCon = New SqlConnection(sqlConnectionString)

Using cmd As New SqlCommand(storedprocedureName, sqlCon)
cmd.CommandType = CommandType.StoredProcedure


Using reader As SqlDataReader = cmd.ExecuteReader()
'Get All column
Dim columnNames = Enumerable.Range(0, reader.FieldCount).[Select](reader.GetName).ToList()

'Create headers
sb.Append(String.Join(",", columnNames))

'Append Line

While reader.Read()
For i As Integer = 0 To reader.FieldCount - 1
Dim value As String = reader(i).ToString()
If value.Contains(",") Then
value = (Convert.ToString("""") & value) + """"
End If

sb.Append(value.Replace(Environment.NewLine, " ") + ",")
sb.Length -= 1
' Remove the last comma
End While
End Using
End Using

End Using
Catch ex As Exception
Throw ex
End Try
Return sb
End Function

Comments or Responses

Login to post response