c# read text string line by line code example

Example 1: c# read file line by line

int counter = 0;  
string line;  
  
// Read the file and display it line by line.  
System.IO.StreamReader file =
    new System.IO.StreamReader(@"c:\test.txt");  
while((line = file.ReadLine()) != null)  
{  
    System.Console.WriteLine(line);  
    counter++;  
}  
  
file.Close();  
System.Console.WriteLine("There were {0} lines.", counter);  
// Suspend the screen.  
System.Console.ReadLine();

Example 2: c# C# read text from a certain line number from string

string GetLine(string text, int lineNo) 
{ 
  string[] lines = text.Replace("\r","").Split('\n'); 
  return lines.Length >= lineNo ? lines[lineNo-1] : null; 
}