-1

I would like to know how I can add all the lines in a file (decimals) into a total sum variable.

This is what I have:

decimal numData, numTotal;

StreamReader file1;

file1 = File.OpenText("data1.dat");

numData = file1.ReadLine();

if(decimal.TryParse(file1.ReadLine().Trim(), out sumData))
{
numTotal = numData;
listBoxNums.Items.Add(numTotal.ToString("c2"));
}

but it only gives me the first line of the file, is there a way to sum all the lines in the file?

  • 1
    Use a loop until ReadLine() returns `null`. Sigh. – Hans Passant Feb 21 '16 at 08:19
  • Well yes, you're only calling `ReadLine` once (well, twice, for no terribly obvious reason). I'd suggest using `File.ReadLines` to retrieve an `IEnumerable`. If you just want a *single* result (the sum) you can just use LINQ to do that. – Jon Skeet Feb 21 '16 at 08:19
  • _"but it only gives me the first line of the file, is there a way to sum all the lines in the file?"_ - I'd probably be more concerned as to why it doesn't compile – MickyD Feb 21 '16 at 08:19

3 Answers3

1

Use foreach and ReadLines instead of ReadLine will do the trick

decimal numData, numTotal;

StreamReader filne1;

file1 = File.OpenText("data1.dat");

foreach (var line in file1.ReadLines()){
    if(decimal.TryParse(file1.ReadLine().Trim(), out numData))
    {
        numTotal += numData;
    }

}

listBoxNums.Items.Add(numTotal.ToString("c2"));

Like what you may already infer, ReadLines will fetch all the lines from the file - but one by one - instead of ReadLine.

Do not confuse ReadLines with ReadAllLines. Both will read all the lines from a file, but ReadAllLines will do it at once.

For small sized file, ReadAllLines is okay. For larger sized file, it may give some problem. In general, use ReadLines as long as it is okay to fetch the line one by one.

Ian
  • 29,380
  • 18
  • 66
  • 103
  • It seems strange to add all the intermediate results to the listbox, yes I know, it is how the OP has coded it, but I would add an advice about that. – Steve Feb 21 '16 at 08:27
  • @Steve ah, yes. It would be more meaningful if we just put the results in the listbox, updated. – Ian Feb 21 '16 at 08:33
1

This is how you do it.

Since you are reading one line at a time, you to loop until you have reached end of file.

var file1 = File.OpenText("data1.dat");

// you need to loop until you reach end of file.
while(file.Peek() >= 0)
{
    if(decimal.TryParse(file1.ReadLine().Trim(), out sumData))
    {
        numTotal += sumData;
    }
}
listBoxNums.Items.Add(numTotal.ToString("c2"));

file1.Dispose();
Parimal Raj
  • 19,697
  • 9
  • 69
  • 107
1

I think, you need something like that:

decimal numData, numTotal = 0;

StreamReader file1 = File.OpenText("data1.dat");

string line;
while ((line = file1.ReadLine()) != null)
{
    decimal.TryParse(line.Trim(), out numData);
    numTotal += numData;
    listBoxNums.Items.Add(numTotal.ToString("c2"));
}
Eva
  • 439
  • 2
  • 8