For various reasons, you may want to read a file line by line a file and save it to a List<> collection. Here, that code will help you for it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Program { static void Main(string[] args) { string[] lines; var list = new List<string>(); var fileStream = new FileStream(@"D:\sample\file.txt", FileMode.Open, FileAccess.Read); //adding lines to a LIST using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { string line; while ((line = streamReader.ReadLine()) != null) { list.Add(line); } } lines = list.ToArray(); //reading the LIST foreach (var item in list) { Console.WriteLine(item); } Console.WriteLine("\nPress any key to exit."); Console.ReadKey(); } } |