problem accessing array length

  • Thread starter Thread starter CCLeasing
  • Start date Start date
C

CCLeasing

I have a function that generates an error if the file it is operating
on is empty. I would like to add some error protection in. The
modification i tried to make to the function i've included in the
commented section in the code. However the ide underlines the
lines.Length in red indicating that it isn't accesible why is this? how
else can i code this?


private bool CheckDuplicates(string filepath, string linetocheck)
{
string[] lines = File.ReadAllLines(filepath);

/// i would like to do something like....
/// if lines.Length < 0 Then Messagebox("file is empty");
/// else

if (lines[lines.Length - 1] == linetocheck)
return true;
else
return false;
}
 
CCLeasing said:
I have a function that generates an error if the file it is operating
on is empty. I would like to add some error protection in. The
modification i tried to make to the function i've included in the
commented section in the code. However the ide underlines the
lines.Length in red indicating that it isn't accesible why is this? how
else can i code this?


private bool CheckDuplicates(string filepath, string linetocheck)
{
string[] lines = File.ReadAllLines(filepath);

/// i would like to do something like....
/// if lines.Length < 0 Then Messagebox("file is empty");
/// else

if (lines.Length < 0 )
Messagebox("file is empty");

Is is what you wanted to do..
if (lines[lines.Length - 1] == linetocheck)
return true;
else
return false;
}
 
I suspect this relates to something that has been lots in your cut/paste...
following compiles fine. See also the comment about FileInfo, and note that
it would generally be better to throw an exception *unless* you are already
at the UI handler level. You could also look at ReadLine, which avoids
having them all in memory... possibly not much in it (except for big files),
though...

Marc

using System;
using System.IO;
using System.Windows.Forms;
class Test
{
private bool CheckDuplicates(string filepath, string linetocheck)
{
// could also look at new FileInfo(filepath).Length
string[] lines = File.ReadAllLines(filepath);

if(lines.Length == 0) {
MessageBox.Show("File is empty");
}

if (lines[lines.Length - 1] == linetocheck)
return true;
else
return false;
}
}
 
I dropped an else... force of habit from throwing ;-p

bool result;
if(lines.Length == 0) {
MessageBox.Show("File is empty");
result = false;
} else {
result = lines[lines.Length - 1] == linetocheck;
}
return result;

Marc
 
Back
Top