合并 中的 2 行.CSV 文件,使用 StreamReader

本文关键字:使用 StreamReader 文件 CSV 中的 合并 | 更新日期: 2023-09-27 18:34:10

我目前正在尝试合并.csv文件中的一些行。该文件遵循由","拆分的特定格式,最后一个元素使用 ' ascii 代码。这意味着最后一个元素被放在一个新行上,我返回一个只有一个元素的数组。我希望将此元素与其上方的行合并。

所以我的台词是:

192.168.60.24, ACD_test1,86.33352, 07/12/2014 13:33:13, False, Annotated, True,"Attribute1
Attribute 2
Attribute 3"
192.168.60.24, ACD_test1,87.33352, 07/12/2014 13:33:13, False, Annotated, True

是否可以将新线属性与上面的线合并/连接?

我的代码如下所示:

var reader = new StreamReader(File.OpenRead(@path));
                string line1 = reader.ReadLine();
                if (line1.Contains("Server, Tagname, Value, Timestamp, Questionable, Annotated, Substituted"))
                {
                    while (!reader.EndOfStream)
                    {
                        List<string> listPointValue = new List<string>();
                        var line = reader.ReadLine();
                        var values = line.Split(',');
                        if (values.Count() < 2)
                        {
                            //*****Trying to Add Attribute to listPointValue.ElememtAt(0) here******
                        }
                        else
                        {
                            foreach (string value in values)
                            {
                            listPointValue.Add(value);
                            }
                            allValues.Add(listPointValue);
                        }
                    }
                   // allValues.RemoveAt(0);
                    return allValues;
                }

合并 中的 2 行.CSV 文件,使用 StreamReader

我想你想在你做allValues.Add之前阅读下一行。这样,您就可以决定是否将上一行添加到 allValues(开始新行)。这让你明白我的意思:

var reader = new StreamReader(File.OpenRead(@path));
string line1 = reader.ReadLine();
if (line1.Contains("Server, Tagname, Value, Timestamp, Questionable, Annotated, Substituted"))
{
    List<string> listPointValue = new List<string>();
    // Add first line to listPointValue
   var line = reader.ReadLine();
   var values = line.Split(',');
   foreach (string value in values)
   {
        listPointValue.Add(value);
   }
   while (!reader.EndOfStream)
   {
        // Read next line
        line = reader.ReadLine();
        values = line.Split(',');
        // If next line is a full line, add the previous line and create a new line
        if (values.Count() > 1)
        {
            allValues.Add(listPointValue);
            listPointValue = new List<string>();
        }
        // Add values to line
        foreach (string value in values)
        {
             listPointValue.Add(value);
        }
    }
    allValues.Add(listPointValue);
}