2012-06-14 57 views
0

我有一个处理一些大型CSV文件的系统。无法从封闭的TextReader读取

现在已经出现这种情况,这些文件在实际的逗号分隔内容之前可能有一些没有分隔的无用行。

我采取的方法是创建一个临时阅读器,以确定多余的行数,然后将工作的TextReader移动到准备处理的行数上。

我的代码如下:

private static TextReader PrepareReader(TextReader reader) 
    { 
     // Variables 
     TextReader tmpReader = reader; 
     Int32 superfluousLineCount = 0; 

     // Determine how many useless lines we have 
     using (tmpReader) 
     { 
      string line; 
      string headerIdentifier = "&1,"; 
      while ((line = tmpReader.ReadLine()) != null) 
      { 
       // Check if the line starts with the header row identifier 
       if (line.Substring(0, 3) != headerIdentifier) 
       { 
        // Increment the superfluous line counter 
        superfluousLineCount++; 
       } 
       else 
       { 
        break; 
       } 
      } 
     } 

     // Move the source reader through how many lines we want to ignore 
     using (reader) 
     { 
      for (int i = superfluousLineCount; i > 0; i--) 
      { 
       reader.ReadLine(); 
      } 
     } 

     // Return 
     return reader; 
    } 

然而,在这部分代码的reader.ReadLine();

for (int i = superfluousLineCount; i > 0; i--) 
{ 
reader.ReadLine(); 
} 

...抛出以下异常

无法读取从一个封闭的TextReader。 的ObjectDisposedException在mscorlib程序 方法: 空隙ReaderClosed()

堆栈跟踪: 在System.IO .__ Error.ReaderClosed() 在System.IO.StreamReader.ReadLine() 在CsvReader.PrepareReader(TextReader的阅读器)在CsvReader.cs中:第93行

任何建议非常感谢。此外,是我的挑战的最佳途径?

备注:Framework 2.0

谢谢。

回答

7

当您使用using (tmpReader)将关闭tmpReader(引用同一个对象reader一样),所以当你试着从在循环reader阅读,它是封闭的。

最好的办法就是组合两个循环。正弦你只想跳过线条,我会认为第一个循环的逻辑就足够了。

+1

门外。这行'TextReader tmpReader = reader;'是完全没有意义的。 –

+0

谢谢,现在已经指出,这是非常有意义的。是否可以在不询问文件的情况下复制* TextReader? – Ste

+0

查看[this SO thread](http://stackoverflow.com/questions/831417/how-do-you-reset-ac-sharp-net-textreader-cursor-back-to-the-start-point)for你可以试试 – Attila

0

我想你只需要做到这一点(标准化/纠正它,我做了一些简化,没有任何编译或测试):

// edit 
    private static TextReader PrepareReader(TextReader reader, out string outLine) 
    { 



      string line; 
      string headerIdentifier = "&1,"; 
      while ((line = reader.ReadLine()) != null) 
      { 
       // Check if the line starts with the header row identifier 
       if (line.Substring(0, 3) != headerIdentifier) 
       { 
        // ... do nothing 
       } 
       else 
       { 
        // edit 
        outLine = line; 
        break; 
       } 
      } 

    } 

督察使用输入参考,并移动您希望读者。

注意关闭你的读者这种方法

+0

但是有了这个,我不会已经通过了我想要处理的第一行吗? – Ste

+0

请参阅编辑操作的评论 –