我们与另一个系统集成,该系统依赖于来回传递 CSV 文件(非常老派)。
结构一般是:
ID, Name, PhoneNumber, comments, fathersname
1, tom, 555-1234, just some random text, bill
2, jill smith, 555-4234, other random text, richard
我们经常看到这个:
3, jacked up, 999-1231, here
be dragons
amongst us, ted
我关心的主要问题是检测记录中间是否出现换行符 (\n
),而这是记录终止符。
无论如何我可以预处理它以可靠地修复它吗?
请注意,我们对其他系统发出的内容零控制。
最佳答案
所以你应该能够或多或少地做这样的事情:
for (int i = 0; i < lines.Count; i++)
{
var fields = lines[i].Split(',').ToList();
while (fields.Count < numFields)//here be dragons amonst us
{
i++;//include next line in this line
//check to make sure we haven't run out of lines.
//combine end of previous field with start of the next one,
//and add the line break back in.
var innerFields = lines[i].Split(',');
fields[fields.Count - 1] += "\n" + innerFields[0];
fields.AddRange(innerFields.Skip(1));
}
//we now know we have a "real" full line
processFields(fields);
}
(为简单起见,我假设所有行都在开始时读入;我假设您可以将其更改为足够轻松地延迟获取每一行。)
关于c# - 解析 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407037/