Parsing CSV File enclosed with quotes in C#

后端 未结 10 1966
一整个雨季
一整个雨季 2021-01-21 05:50

I\'ve seen lots of samples in parsing CSV File. but this one is kind of annoying file...

so how do you parse this kind of CSV

\"1\",1/2/2010,\"The sample (\"adas

10条回答
  •  生来不讨喜
    2021-01-21 06:28

    I found a way to parse this malformed CSV. I looked for a pattern and found it.... I first replace (",") with a character... like "¤" and then split it...

    from this:

    "Annoying","CSV File","poop@mypants.com",1999,01-20-2001,"oh,boy",01-20-2001,"yeah baby","yeah!"
    

    to this:

    "Annoying¤CSV File¤poop@mypants.com",1999,01-20-2001,"oh,boy",01-20-2001,"yeah baby¤yeah!"
    

    then split it:

    ArrayA[0]: "Annoying //this value will be trimmed by replace("\"","") same as the array[4]
    ArrayA[1]: CSV File
    ArrayA[2]: poop@mypants.com",1999,01-20-2001,"oh,boy",01-20-2001,"yeah baby
    ArrayA[3]: yeah!"
    

    after splitting it, I will replace strings from ArrayA[2] ", and ," with ¤ and then split it again

    from this

    ArrayA[2]: poop@mypants.com",1999,01-20-2001,"oh,boy",01-20-2001,"yeah baby
    

    to this

    ArrayA[2]: poop@mypants.com¤1999,01-20-2001¤oh,boy¤01-20-2001¤yeah baby
    

    then split it again and would turn to this

    ArrayB[0]: poop@mypants.com
    ArrayB[1]: 1999,01-20-2001
    ArrayB[2]: oh,boy
    ArrayB[3]: 01-20-2001
    ArrayB[4]: yeah baby
    

    and lastly... I'll split the Year only and the date from ArrayB[1] with , to ArrayC

    It's tedious but there's no other way to do it...

提交回复
热议问题