-
March 30th, 2010, 08:03 AM
#1
[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);
}
}
-
March 30th, 2010, 09:47 PM
#2
Re: StreamReader.ReadLine() ERROR!
is there a blank line at the end of your file?
===============================
My Blog
-
March 31st, 2010, 02:30 AM
#3
Re: StreamReader.ReadLine() ERROR!
And what are the SplitLine() and ConverToLong() methods doing?
-
March 31st, 2010, 03:49 AM
#4
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?
-
March 31st, 2010, 05:57 AM
#5
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();
}
}
-
March 31st, 2010, 08:43 AM
#6
Re: StreamReader.ReadLine() ERROR!
Works perfectly!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|