[RESOLVED] StreamReader.ReadLine() ERROR!
I am reading values from a selected textfile and then displaying them in a textbox present on my Windows.Form. After my whole textfile has been looped through, the last line in my textfile is repeated again and then I receive the error message: "Exception: Index out of array range."
Do you know what I could have done wrong in my loop?
Code:
protected void ReadFile()
{
try
{
String line = null;
using (mStreamReader = File.OpenText(mOpenFileDialog.FileName))
{
while ((line = mStreamReader.ReadLine()) != null)
{
SplitLine(line);
ConvertToLong();
}
}
tbxDisplay.Text = msContents;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Re: StreamReader.ReadLine() ERROR!
is there a blank line at the end of your file?
Re: StreamReader.ReadLine() ERROR!
And what are the SplitLine() and ConverToLong() methods doing?
Re: StreamReader.ReadLine() ERROR!
Amazing, I took away the two blank lines at the end of my file and it worked! How do I prevent this from happening though without manually taking away the blank lines?
Re: StreamReader.ReadLine() ERROR!
change
Code:
while ((line = mStreamReader.ReadLine()) != null)
{
SplitLine(line);
ConvertToLong();
}
into
Code:
while ((line = mStreamReader.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line))
break;
SplitLine(line);
ConvertToLong();
}
But this will also break the operation if there is an blank line in the middle of the file. You could also ignore blank lines
Code:
while ((line = mStreamReader.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line)) //only execute if line is not empty
{
SplitLine(line);
ConvertToLong();
}
}
Re: StreamReader.ReadLine() ERROR!