2013-10-04 40 views
1

我想从csv读取两列,行由';'分隔。使用单元格内的新行字符读取CSV

我使用的是stram.ReadLine方法,但问题是有些单元格的文本中有新行字符,因此方法ReadLine将该单元格分成几个其他单元格,我怎样才能避免这种情况?为了简化这个模型,可以说我有一列有100行,但其中一些里面有长文本和一些断行,我怎样才能修改这100行而不是更多?

StreamReader aFile = new StreamReader("C:\\dev\\csvReplacment\\szablonDE.csv"); 


      var dane = new List<string>(); 

      string line; 

      while ((line = aFile.ReadLine()) != null) 
      { 
       dane.Add(line); 
      } 
      aFile.Close(); 
+1

你试过沃尔格林代替 – Jonesopolis

+0

沃尔格林?那是什么 ? – kosnkov

+0

你能提供一个内容的例子吗?另外,如果有新行,则可能不希望“ReadLine”,而是直到下一次出现“;”或文件末尾(以先到者为准)。 –

回答

1

假设;标志着一行的末尾:

// Build your final resulting list 
    List<String> dane = new List<String>(); 

    // use StreamReader to read the file 
    using (StreamReader sr = new StreamReader(ms)) 
    { 
     // create a string builder that we can use to store each 
     // line's contents until it's ready to be added to dane 
     StringBuilder builder = new StringBuilder(); 
     // buffer char 
     Char c; 
     // read the stream character by character 
     while (!sr.EndOfStream) 
     { 
      c = (Char)sr.Read(); 
      // if it's `;` it's the end of a row, so add it to 
      // dane and reset the line's contents 
      if (c == ';') 
      { 
       dane.Add(builder.ToString()); 
       builder.Clear(); 
      } 
      // avoid reading in superfluous whitespace before we 
      // begin reading a line 
      else if (builder.Length == 0 && Char.IsWhiteSpace(c)) 
      { 
       continue; 
      } 
      // concatenate the current character to our line 
      else 
      { 
       builder.Append(c); 
      } 
     } 
     // if there's a final row, add it to dane 
     if (builder.Length > 0) 
     { 
      dane.Add(builder.ToString()); 
     } 
    } 

    // dane now contains each line's contents. 

你也许可以优化这一点,并在同一时间在1024个字符阅读并搜索内部;,但是这仅仅是一个原始示例向您展示如何开始。

相关问题