Reading CSV files using C#

后端 未结 12 2789
野的像风
野的像风 2020-11-21 22:49

I\'m writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For ex

12条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 23:49

    My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.

    These are the variants I have ran into:

    • quotes are quoted and doubled (excel) i.e. 15" -> field1,"15""",field3
    • quotes are not changed unless the field is quoted for some other reason. i.e. 15" -> field1,15",fields3
    • quotes are escaped with \. i.e. 15" -> field1,"15\"",field3
    • quotes are not changed at all (this is not always possible to parse correctly)
    • delimiter is quoted (excel). i.e. a,b -> field1,"a,b",field3
    • delimiter is escaped with \. i.e. a,b -> field1,a\,b,field3

    I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.

    In my projects I now use either the VB TextFieldParser or a custom splitter.

提交回复
热议问题