是否有Microsoft.VisualBasic.FileIO.TextFieldParser的写入副本?

时间:2012-10-18 20:23:30

标签: .net-4.0

我需要创建一个新的CSV文件。编写我自己的例程并不是一项大任务,但基类库中有一个例程吗?

2 个答案:

答案 0 :(得分:7)

以下是可用于从字符串列表生成一行CSV文件的函数(IEnumerable(Of String)或字符串数​​组也可以使用):

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

答案 1 :(得分:5)

不在框架中,代码太简单了。使用StreamWriter.Write()进行简单的操作,您只需要进行一些提升以正确引用字符串。它只需要几行:

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