You can read the lines of the file in a much easier way by using File.ReadAllLines()
. This method will read the file and create an array where each line of the file represents an array element.
After that, just convert each line to number. The Select
method maps each item in the source array (the array returned by ReadAllLines
, in this case) according to the function passed by parameter. The function there only converts each element ( l
represents each element) to number.
Then, at the end of this, we have the array numeros
with N elements (where N is the number of rows in the file), where each element is the numeric representation of each line of the file initial.
After that, just look for the largest number in array .
This can be found by using LINQ, using the Max
.
// using System.Linq; <<-- Inclua isto nos using
var numeros = File.ReadAllLines(caminhoArquivo).Select(l => Convert.ToInt32(l)).ToArray();
var maior = numeros.Max(n => n);
Console.WriteLine($"O maior número no arquivo é {maior}");
For purposes of understanding, the code above is equivalent to this
var linhas = File.ReadAllLines(caminhoArquivo);
var numeros = new List<int>();
foreach(var l in linhas)
numeros.Add(Convert.ToInt32(l));
int maior = 0;
foreach(var numero in numeros)
maior = numero > maior ? numero : maior;
Console.WriteLine($"O maior número no arquivo é {maior}");