You can read the file lines in a much easier way using File.ReadAllLines()
. This method will read the file and create a array where each line in the file represents an element in the array.
After that just convert each row to number. The method Select
maps each item of array of origin (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) for number.
So, at the end of that, you have the array numeros
with N elements (where N is the number of lines in the file), where each element is the numerical representation of each line in the initial file.
After that just look for the largest number on array.
This can be found using LINQ, with the method 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 the purpose of understanding, the above code 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}");
What types of information does your text file contain? Only numbers? Does it have text as well? Is the information being stored by default? Show an example of your file please?
– Pedro Paulo
this one has only numbers
– Rui Febra