VB.net code to convert a data reader to stringbuilder

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

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

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

sqlCon.Open()

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
sb.AppendLine()

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, " ") + ",")
Next
sb.Length -= 1
' Remove the last comma
sb.AppendLine()
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