Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a write counterpart to Microsoft.VisualBasic.FileIO.TextFieldParser?

Tags:

.net-4.0

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?

like image 755
Chad Avatar asked Oct 18 '12 20:10

Chad


2 Answers

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
like image 116
Evgeny Gorb Avatar answered Oct 31 '22 17:10

Evgeny Gorb


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
like image 25
Hans Passant Avatar answered Oct 31 '22 18:10

Hans Passant