C# 读取 csv 文中包含逗号,,的处理

因为csv读取的方式就是每行按照逗号分隔,如果正文中有逗号,那么这列字段就会被引号包裹,这里给出代码,针对这种情况的处理:

 1         /// <summary>
 2         /// 跳过引号中的逗号,进行逗号分隔(字段内容中的逗号不参与分隔)
 3         /// </summary>
 4         /// <param name="strLine"></param>
 5         /// <returns></returns>
 6         public static string[] CSVstrToArry(string splitStr)
 7         {
 8             var newstr = string.Empty;
 9             List<string> sList = new List<string>();
10 
11             bool isSplice = false;
12             string[] array = splitStr.Split(new char[] { ',' });
13             foreach (var str in array)
14             {
15                 if (!string.IsNullOrEmpty(str) && str.IndexOf('"') > -1)
16                 {
17                     var firstchar = str.Substring(0, 1);
18                     var lastchar = string.Empty;
19                     if (str.Length > 0)
20                     {
21                         lastchar = str.Substring(str.Length - 1, 1);
22                     }
23                     if (firstchar.Equals("\"") && !lastchar.Equals("\""))
24                     {
25                         isSplice = true;
26                     }
27                     if (lastchar.Equals("\""))
28                     {
29                         if (!isSplice)
30                             newstr += str;
31                         else
32                             newstr = newstr + "," + str;
33 
34                         isSplice = false;
35                     }
36                 }
37                 else
38                 {
39                     if (string.IsNullOrEmpty(newstr))
40                         newstr += str;
41                 }
42 
43                 if (isSplice)
44                 {
45                     //添加因拆分时丢失的逗号
46                     if (string.IsNullOrEmpty(newstr))
47                         newstr += str;
48                     else
49                         newstr = newstr + "," + str;
50                 }
51                 else
52                 {
53                     sList.Add(newstr.Replace("\"", "").Trim());//去除字符中的双引号和首尾空格
54                     newstr = string.Empty;
55                 }
56             }
57             return sList.ToArray();
58         }

感谢:

https://blog.csdn.net/qq_36894527/article/details/97136252