I am using a StreamReader
to read lines from a text file. For each line I have specific operations that are performed.
Example:
System.IO.StreamReader file = new System.IO.StreamReader(fileDirectory); //Open StreamReader
while ((inFileString = file.ReadLine()) != null)
{
if(something)
{ do stuff... }
}
My problem occurs after the last line is read, because the code inside the while
loop becomes inaccessible. It's basically like I need to be allowed to go through the while
loop one more time, after it automatically exits. How do I perform my operations on the last line read from the file?
(I could just replicate the operations outside of the loop, but I figured that would be inefficient...)
I think something like this looks acceptable.
using (StreamReader file = new StreamReader(@"D:\Downloads\testfile.txt"))
{
string str = "";
while ((str = file.ReadLine()) != null || str == null)
{
if (str == null)
{
Console.WriteLine("Hey! We've already passed the EOF!");
break;
}
Console.WriteLine(str);
}
}