In this article I will show you how to read a text file line by line in c# in console application.
Some of my previous articles are as follows: How to get a User's Client IP address in ASP.NET using C#.Net, How To Make a Single Row of DataGridview Bold Using C#.Net in Windows Application, How to Get the Full Path of FileUpload Control in Asp.Net.
Now for this application first we will create a new console application, add the below code in your console application.
C#.Net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace DemoConsoleApplication
{
class Program
{
/// <summary>
/// How to Read a Text File Line by Line in C# in Console Application
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
int totallinecounter = 0;
string textfileline;
/*Code to Read the file.*/
StreamReader objstreamreaderfile = new StreamReader(@"D:\DemoTextFile.txt");
while ((textfileline = objstreamreaderfile.ReadLine()) != null)
{
Console.WriteLine(textfileline);
totallinecounter++;
}
objstreamreaderfile.Close();
System.Console.WriteLine("Total no of lines in text file is {0}.", totallinecounter);
System.Console.ReadLine();
}
}
}
|
VB.Net
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.IO
Namespace DemoConsoleApplication
Class Program
''' <summary>
''' How to Read a Text File Line by Line in C# in Console Application
''' </summary>
''' <param name="args"></param>
Private Shared Sub Main(ByVal args As String())
Dim totallinecounter As Integer = 0
Dim textfileline As String
'Code to Read the file.
Dim objstreamreaderfile As New StreamReader("D:\DemoTextFile.txt")
While (InlineAssignHelper(textfileline, objstreamreaderfile.ReadLine())) <> Nothing
Console.WriteLine(textfileline)
System.Math.Max(System.Threading.Interlocked.Increment(totallinecounter), totallinecounter - 1)
End While
objstreamreaderfile.Close()
System.Console.WriteLine("Total no of lines in text file is {0}.", totallinecounter)
System.Console.ReadLine()
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
End Class
End Namespace
|
Now we will first create a new text file.
Now we will run the application.
DOWNLOAD
0 comments:
Please let me know your view