You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.NET中利用回车换行符解析含逗号的CSV文件

正确解析含特殊字符的CSV文件方案

在VB.NET中解析包含逗号、回车换行的CSV时,TextFieldParser本身支持处理被引号包裹的字段,只需确保配置正确并合理组织数据绑定逻辑。以下是修正后的代码:

步骤1:定义数据模型类

首先创建一个类来存储每行CSV的数据,方便后续绑定:

Public Class Customer
    Public Property ID As String
    Public Property Name As String
    Public Property Description As String
End Class

步骤2:修正解析逻辑

使用Using语句确保资源正确释放,同时启用字段引号包裹支持(默认已开启,显式设置更稳妥),并批量收集数据后再绑定:

Imports Microsoft.VisualBasic.FileIO
Imports System.Collections.Generic

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' 创建列表存储所有数据
        Dim customerList As New List(Of Customer)()

        ' 使用Using自动释放TextFieldParser资源
        Using tfp As New TextFieldParser("Z:\Downloads\test.csv")
            tfp.TextFieldType = FieldType.Delimited
            tfp.Delimiters = New String() {","}
            ' 显式开启引号包裹字段支持,处理含逗号/换行的字段
            tfp.HasFieldsEnclosedInQuotes = True

            ' 跳过表头行
            tfp.ReadLine()

            While Not tfp.EndOfData
                Try
                    Dim fields = tfp.ReadFields()
                    ' 确保字段数量正确(防止CSV格式错误)
                    If fields.Length >= 3 Then
                        Dim customer As New Customer()
                        customer.ID = fields(0)
                        customer.Name = fields(1)
                        customer.Description = fields(2)
                        customerList.Add(customer)
                    End If
                Catch ex As MalformedLineException
                    ' 处理格式错误的行
                    MessageBox.Show($"错误行内容:{tfp.ErrorLine}{vbCrLf}错误信息:{ex.Message}")
                End Try
            End While
        End Using

        ' 将整个列表绑定到数据源
        CustomerBindingSource.DataSource = customerList
    End Sub
End Class

关键说明

  • HasFieldsEnclosedInQuotes = True:该属性让TextFieldParser识别被双引号包裹的字段,即使字段内包含逗号、回车(CarriageReturn)或换行(LineFeed),也会被完整解析为单个字段值。
  • 使用数据模型类:避免直接绑定字符串数组,让数据结构更清晰,也方便后续UI控件的字段映射。
  • 错误处理:添加Try-Catch捕获格式错误的行,避免程序崩溃。
  • 批量绑定:在循环外设置数据源,避免每次循环覆盖绑定内容,确保所有数据都能显示。

内容的提问来源于stack exchange,提问作者matt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 21:59:55