On some machines, but not on others, I get a System.ObjectDisposedException using this class.
class LogComparer { private string firstFile; private string secondFile; private IEnumerable<string> inFirstNotInSecond; private IEnumerable<string> inSecondNotInFirst; public LogComparer(string firstFile, string secondFile) { if (!File.Exists(firstFile) || !File.Exists(secondFile)) { throw new ArgumentException("Input file location is not valid."); } this.firstFile = firstFile; this.secondFile = secondFile; GenerateDiff(); } public string FirstFile { get { return firstFile; } } public bool IsEqual { get { return inFirstNotInSecond.SequenceEqual(inSecondNotInFirst); } } public string SecondFile { get { return secondFile; } } public IEnumerable<string> InFirstNotInSecond { get { return inFirstNotInSecond; } } public IEnumerable<string> InSecondNotInFirst { get { return inSecondNotInFirst; } } private void GenerateDiff() { var file1Lines = File.ReadLines(firstFile); var file2Lines = File.ReadLines(secondFile); inFirstNotInSecond = file1Lines.Except(file2Lines); inSecondNotInFirst = file2Lines.Except(file1Lines); } }
System.ObjectDisposedException: Cannot read from a closed TextReader. ObjectName: at System.IO.__Error.ReaderClosed() at System.IO.StreamReader.ReadLine() at System.IO.File.<InternalReadLines>d__0.MoveNext() at System.Linq.Enumerable.<ExceptIterator>d__99`1.MoveNext() at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
After changing GenerateDiff() to:
private void GenerateDiff() { var file1Lines = File.ReadLines(firstFile).ToList(); var file2Lines = File.ReadLines(secondFile).ToList(); inFirstNotInSecond = file1Lines.Except(file2Lines); inSecondNotInFirst = file2Lines.Except(file1Lines); }
I cannot throw an exception.
Interestingly, this does not work:
private void GenerateDiff() { var file1Lines = File.ReadLines(firstFile); var file2Lines = File.ReadLines(secondFile); inFirstNotInSecond = file1Lines.Except(file2Lines).ToList(); inSecondNotInFirst = file2Lines.Except(file1Lines).ToList(); }
I am using an instance of this diff class here, for example. No using or Dispose anywhere. No tasks or threads.
if (diff.InSecondNotInFirst.Any(s => !s.Contains("bxsr")))
Can someone explain the reason? Thanks.
(We assume that, because of IEnumerable<> implements lazy loading, and the garbage collector closes the reader before I want to access InFirstNotInSecond or InSecondNotInFirst . But with GC.Collect() there is still no exception on some machines. )