C# Read Text File Line-by-Line


Hi friends,
this is a C# code for read the .txt file line by line . which is some the we need to use in our Programming. Hope it will help you...

using System;
using System.IO;

namespace TestReadLine
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"c:\YourFile.txt";
            string line;
            int count = 0;
            if (File.Exists(filePath))
            {
                StreamReader file = null;
                try
                {
                    file = new StreamReader(filePath);
                    while ((line = file.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                        count = count + 1;
                    }
                }
                finally
                {
                    Console.WriteLine("Total No of line is Used :"+count);
                    if (file != null)
                        file.Close();
                }
            }

            Console.ReadLine();
        }
    }
}


-----------------------------------------------------------------------------
This is a Method Use to replace the string in the .txt file

using System.Text.RegularExpressions;

static public void ReplaceInFile(string filePath, string searchText, string replaceText)
        {
            StreamReader reader = new StreamReader(filePath);
            string content = reader.ReadToEnd();
            reader.Close();

            content = Regex.Replace(content, searchText, replaceText);

            StreamWriter writer = new StreamWriter(filePath);
            writer.Write(content);
            writer.Close();
        }
Regards ,
Rajesh

0 comments: