I have a problem that I have been trying to figure out for hours now, and I am sure it’s something simple.
Here is the code (extra junk removed as it’s not a problem).
foreach (String itemChecked in fightsList.CheckedItems)
{
try
{
Thread.Sleep(50);
using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.ASCII))
{
while ((line = reader.ReadLine()) != null)
{
// do all stuff to lines here...
}
}
}
catch (Exception error)
{
errorText.Text = error.ToString();
}
}
// foreach done here.
I am reading a text file, obvious from StreamReader, but when the foreach loop rolls to the second iteration, it fails before running the StreamReader and stops the foreach loop.
The first loop runs great.
I am thinking it’s a problem because the ‘StreamReader reader = new’ already exists and it cannot create a new one?
The foreach is a string checkedBox. StreamReader is reading the same file for all instances in the loop, I just handle where to start and stop per each. My error catching does not get anything, and the application does not crash.
The problem is not in the code you have posted. I would suggest allocating the file stream as a separate step and putting a break point on the line where you are passing it into the StreamReader. On the second pass make sure everything (filename, length, etc) looks OK on the underlying stream your problem is inside of the loop otherwise it is elsewhere in your code.
your also better off reorganizing your code like
since this will make the expensive operation (file IO) happen as few times as possible, but that isn’t why you are having this specific problem.