2014-12-12 2 views
1

현재 일부 줄을 .csv 파일로 병합하려고합니다. 이 파일은 ","로 분리 된 특정 형식을 따르고 마지막 요소는 ASCII 코드를 \ n 사용합니다. 이것은 마지막 요소가 새로운 라인에 놓이고 하나의 요소 만 가진 배열을 반환한다는 것을 의미합니다. 이 요소를 위의 줄과 병합하려고합니다.StreamReader를 사용하여 .CSV 파일에서 2 줄을 병합하십시오.

그래서 내 라인은 다음과 같습니다

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

답변

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); 
} 
관련 문제