I need to create a new CSV file. Writing my own routine wouldn't be a big task, but is there a routine in the Base Class Library for this?
Here is the function you can use to generate a row of CSV file from string list (IEnumerable(Of String) or string array can be used as well):
Function CreateCSVRow(strArray As List(Of String)) As String
Dim csvCols As New List(Of String)
Dim csvValue As String
Dim needQuotes As Boolean
For i As Integer = 0 To strArray.Count() - 1
csvValue = strArray(i)
needQuotes = (csvValue.IndexOf(",", StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf("""", StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf(vbCrLf, StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf(" ", StringComparison.InvariantCulture) = 0 _
OrElse csvValue.IndexOf(" ", StringComparison.InvariantCulture) = csvValue.Length-1)
csvValue = csvValue.Replace("""", """""")
csvCols.Add(If(needQuotes, """" & csvValue & """", csvValue))
Next
Return String.Join(",", csvCols.ToArray())
End Function
Not in the framework, the code is too simple. Trivially done with StreamWriter.Write(), you only need to do a wee bit of lifting to properly quote a string. It takes just a handful of lines:
Module CsvWriter
Public Sub WriteCsvLine(ByVal out As System.IO.TextWriter, ByVal ParamArray Values() As Object)
For ix As Integer = 0 To Values.Length - 1
If ix > 0 Then out.Write(",")
If TypeOf (Values(ix)) Is String Then
out.Write("""" + CStr(Values(ix)).Replace("""", """""") + """")
Else
out.Write(Values(ix).ToString())
End If
Next
out.WriteLine()
End Sub
End Module
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With