VB.Net - Output SQL Query Results to CSV File

Good Day Experts!

I have little project here that seems pretty straightforward.  I need to query a SQL Server database and get a resultset(not sure whether I am going to use a DataReader or DataTable).
When I loop through the results, I need to write each record to a CSV file.  

I have not done this before so I have searched the net and found differing iterations.
Do you have any recommended reference sites that I could check out?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can write some methods that would do this. Here's a quick and dirty one, haven't tested it. Takes a DataTable as input, and outputs CSV with the column names as headers.

Private Function GetCSVFromTable(table As DataTable) As String
	Dim csvString = New StringBuilder()
	For i As Integer = 0 To table.Columns.Count - 1
		csvString.Append(If(table.Columns.Count - 1 Is i, vbLf, ","))
	For Each row As var In table.AsEnumerable()
		For i As Integer = 0 To table.Columns.Count - 1
			csvString.Append(If(table.Columns.Count - 1 Is i, vbLf, ","))
	Return csvString.ToString()
End Function

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jimbo99999Author Commented:
Excellent information. I have it working now!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.