How to make an array by importing lines from a file?
This will give you all the lines from the file:
var lines = File.ReadAllLines(@"PathToYourFile");
The above reads all lines from a file into memory. There is another method that will read the lines one by one as necessary:
var lines = File.ReadLines(@"PathToYourFile");
This returns an IEnumerable<string> . For example, let's say your file has 1000 lines, ReadAllLines will read all 1000 lines in memory. But ReadLines will read them 1 on 1 as needed. Therefore, if you do this:
var lines = File.ReadLines(@"PathToYourFile"); var line1 = lines.First(); var lastLine = lines.Last();
It will only read the first and last line in memory, even if your file has 1000 lines.
So when to use the ReadLines method?
Let's say you need to read a file that has 1000 lines, and the only lines that you are interested in reading are from 900 to 920, then you can do this:
var lines = File.ReadLines(@"PathToYourFile"); var line900To920 = lines.Skip(899).Take(21);
source share