无法从封闭的TextReader中读取

Ste*_*Ste 0 c# .net-2.0

我有一个处理一些大型CSV文件的系统.

现在出现了这样的情况:这些文件可能在实际以逗号分隔的内容之前有许多无分隔且无价值的行.

我采取的方法是创建一个临时读取器,以确定多余行的数量,然后在准备好处理的那些行上移动工作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;
    }
Run Code Online (Sandbox Code Playgroud)

但是,reader.ReadLine();在这部分代码中:

for (int i = superfluousLineCount; i > 0; i--)
{
reader.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

...抛出以下异常

无法从封闭的TextReader中读取.mscorlib中的ObjectDisposedException方法:Void ReaderClosed()

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

任何建议都非常感谢.此外,是我挑战的最佳方式吗?

注意:Framework 2.0

谢谢.

Att*_*ila 7

当你使用using (tmpReader)它时它将关闭tmpReader(它引用相同的对象reader),所以当你尝试reader在循环中读取时,它将被关闭.

最好的办法是将两个循环结合起来.你只想跳过线,我认为第一个循环的逻辑就足够了.