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

Tags:

C# File.ReadLines() .net 4.0C# SystemIOFileReadAllLines() methodRead Text File in (C#.net or VB.net)C# XML XmlReaderC# Delete All Files In DirectoryAsp.net delete file file on Server C#.net and VB.net codeC# Get File SizeC# Read CSV FileASP.net File Handling(c#) write to text fileOnline html editor online JavaScript editor

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.