TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# File.ReadLines, Use foreach Over Strings

Invoke the File.ReadLines method from System.IO and loop over each line as a string.
File.ReadLines. This method reads lines on demand. We use it in a foreach-loop, looping over each line as a string. The program reads in another line before each iteration of the foreach-loop.File
To begin, this program calls the File.ReadLines method in the foreach loop iteration block. The File.ReadLines method is only called once. Then the IEnumerable<string> is used to pull in more data.

Print: The program successfully prints the data found in the file.txt file in the C directory.

Important: With File.ReadLines, the foreach-loop is the best syntax as it avoids copying the IEnumerable to another collection in memory.

ForeachIEnumerable
C# program that uses File.ReadLines using System; using System.IO; class Program { static void Main() { // Read in lines from file. foreach (string line in File.ReadLines("c:\\file.txt")) { Console.WriteLine("-- {0}", line); } } } Output -- Line1 -- Line2 -- Line3 -- Another line. -- Last line.
ReadAllLines. ReadLines and ReadAllLines are implemented differently. ReadLines uses an enumerator to read each line only as needed. On the other hand, ReadAllLines reads the entire file into memory and then returns an array of those lines.
If the file is large, the File.ReadLines method is useful because it will not need to keep all the data in memory at once. Also, if your program exits the loop early, the File.ReadLines is better because no further IO will be needed.

Thus: The File.ReadAllLines method is best if you need the entire array. An example of it is available.

File.ReadAllLines
Summary. The File.ReadLines method is similar to using the StreamReader type and the ReadLine method in a loop. It is a different interface to that functionality. With it, you can use a simple foreach loop to read in an entire file line-by-line.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf