C# Read File Line By Line

C# Read File Line By Line C# Read File Line By Line

To read file line by line using C# program, you need to use ReadLine method of StreamReader instance. Here you will see examples ReadFile line by line with C#.net and VB.net program. It's very basic and useful program when it comes to read small size file. You may have programmatically read the file using basic C language. Here we will see how to perform the same with .net languages.

C# Read File line by line example.

using System;
using System.IO;
namespace Csharp.ReadFile.Line.By.Line.Example
{
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\xxx";
if (!File.Exists(filePath))
{
filePath = filePath + @"\" + "Readme.txt";
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader reader = new StreamReader(fs);
string line = string.Empty;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine( line );
}
Console.ReadLine();
}
}
}
}

Vb.net program to read file line by line.

In VB.net you can use the ReadLine method of StreamReader as shown in below snippet. It's converted C# program using online tool. You may find it difficult to understand or read.

Imports System.IO
Namespace Csharp.ReadFile.Line.By.Line.Example
Class Program
Private Shared Sub Main(args As String())
Dim filePath As String = "C:\xxx"
If Not File.Exists(filePath) Then
filePath = filePath & "\" & "Readme.txt"
Dim fs As New FileStream(filePath, FileMode.Open)
Dim reader As New StreamReader(fs)
Dim line As String = String.Empty
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
Console.WriteLine(line)
End While
Console.ReadLine()
End If
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class
End Namespace

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Author

Asp.net Day