export array in csv file

tripes

Member
Joined
Apr 16, 2009
Messages
18
Programming Experience
Beginner
hi i want to create a csv file using VB.net 2003 and save the data from an array in it... i have searched everywhere and i did not find a solution.
please help :(
 
Which part of the process do you need help with?
Creating a file?
Creating the content of the file?
 
Below is a simple demonstration of the technique. It assumes that you are using .Net Framework 1.1. If you are still on .Net Framework 1.0, I heartily recommend that you move to 1.1. If that is not possible please let me know and I will re-write the code, since 1.0 does not have StringBuilder.
VB.NET:
		Dim csvFilename as string = "C:\Temp\test.csv"
		Dim stringArray() As String = {"this", "is", "a", "csv", "array"}
		
		Private Sub BtnTestClick(sender As System.Object, e As System.EventArgs)
		    Dim csvOutput As New system.Text.StringBuilder()
		    
		    ' Add each string from the array to the stringbuilder
		    For index As Integer = 0 To Me.stringArray.Length - 1
		        If csvOutput.Length > 0 Then
		            csvOutput.Append(",")
		        End If
		        csvOutput.Append(stringArray(index))
		    Next
		    
		    Dim csvOutputStream as System.IO.FileStream
		    Dim csvOutputWriter As System.IO.StreamWriter
		    Try
		      csvOutputStream = New System.IO.FileStream(Me.csvFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)
		      csvOutputWriter = new System.IO.StreamWriter(csvOutputStream)
		      csvOutputWriter.WriteLine(csvOutput.tostring())
		    Catch exc As exception
		      MessageBox.Show(exc.ToString(), "File Output Error")
		    Finally
		      If Not csvOutputWriter Is Nothing Then
		        csvOutputWriter.Flush()
		        csvOutputWriter.Close()
		      End if
		    End Try
		End Sub

Obviously you will need to change csvFilename to be a path on your computer.
 
VB.NET:
csvOutputWriter.WriteLine(String.Join(","c, stringArray))
 
Excellent!! :)
I saw that some time ago but had completely forgotten it.

Good shout!
 
I don't recommend simply joining the array using a comma; if your data contains a comma, you broke your CSV. OK, so we'll quote all the fields you say.. but them we need to escape the quote characters..

At the very least you should:


csvOutputWriter.WriteLine("""" & String.Join("###", stringArray).Replace("""",""""").Replace("###", """,""") & """")

Where ### is a sequence that never occurs in the data

But really you should use a proper CSV writing library. For reading, I always used JHLib by Jouni Heikniemi, never used the writer but I imagine it's as good..
 
Very good advice.

I always used JHLib by Jouni Heikniemi

I had a very quick look and it seems to have some useful stuff, so I have put it in my Utilities bag for further investigation. For general CSV stuff I currently use FileHelpers Library 2.0 - Marcos Meli, which I find to be very comprehensive.
 

Latest posts

Back
Top