- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to read all the lines one by one in a file
Use ReadAllLines() method to read all the lines one by one in a file.
Let’s say we have a file “new.txt” with the following lines.
One Two Three
Firstly, set the path of the file to be read.
String myPath = "new.txt";
Now add it under a string array to fetch the lines on by one.
String[] fLine = File.ReadAllLines(myPath);
Let’s say you need to fetch the first line. For that.
fLine[0]
The following is the complete example that reads lines one by one in a file.
Example
using System; using System.IO; public class Demo { public static void Main() { String myPath = "new.txt"; String[] fLine; // array of lines in a file fLine = File.ReadAllLines(myPath); // read lines of a file Console.WriteLine("Line 1: "+fLine[0]); Console.WriteLine("Line 2: "+fLine[1]); Console.WriteLine("Line 3: "+fLine[2]); Console.WriteLine("Line 4 "+fLine[3]); } }
Output
Line1: One Line2: Two Line3: Three Line4: Four
Advertisements