How to split csv whose columns may contain ,

前端 未结 8 1312
我寻月下人不归
我寻月下人不归 2020-11-22 06:35

Given

2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,"Corvallis, OR",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34

8条回答
  •  猫巷女王i
    2020-11-22 07:13

    I had a problem with a CSV that contains fields with a quote character in them, so using the TextFieldParser, I came up with the following:

    private static string[] parseCSVLine(string csvLine)
    {
      using (TextFieldParser TFP = new TextFieldParser(new MemoryStream(Encoding.UTF8.GetBytes(csvLine))))
      {
        TFP.HasFieldsEnclosedInQuotes = true;
        TFP.SetDelimiters(",");
    
        try 
        {           
          return TFP.ReadFields();
        }
        catch (MalformedLineException)
        {
          StringBuilder m_sbLine = new StringBuilder();
    
          for (int i = 0; i < TFP.ErrorLine.Length; i++)
          {
            if (i > 0 && TFP.ErrorLine[i]== '"' &&(TFP.ErrorLine[i + 1] != ',' && TFP.ErrorLine[i - 1] != ','))
              m_sbLine.Append("\"\"");
            else
              m_sbLine.Append(TFP.ErrorLine[i]);
          }
    
          return parseCSVLine(m_sbLine.ToString());
        }
      }
    }
    

    A StreamReader is still used to read the CSV line by line, as follows:

    using(StreamReader SR = new StreamReader(FileName))
    {
      while (SR.Peek() >-1)
        myStringArray = parseCSVLine(SR.ReadLine());
    }
    

提交回复
热议问题