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

时间:2014-12-12 10:03:00

标签: c# csv streamreader

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

所以我的路线是:

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;
                }

1 个答案:

答案 0 :(得分:0)

我认为你想在执行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);
}