Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read particular text from file in C# [closed]

Tags:

c#

HI, I am in learning process of C# and trying to read file in my application.But i dont want to read complete file i simply want to read particular text from that file and want to display that text in textbox.... can any please help me in that i want to know the method i can use for reading particular text from file..

Thanks in Advance

Parag Deshpande

like image 948
Parag Deshpande Avatar asked Nov 22 '25 16:11

Parag Deshpande


1 Answers

Assuming these are text files, just open the file and read through it searching for whatever you're searching for. When you find it, stop reading though it. The File.ReadLines() will do this for you and will not read the entire file at the start but give you lines as it goes through it.

var filename = @"c:\path\to\my\file.txt";
var searchTarget = "foo";
foreach (var line in File.ReadLines(filename))
{
    if (line.Contains(searchTarget))
    {   // found it!
        // do something...

        break; // then stop
    }
}

Otherwise, if you're not using C# 4.0, use a StreamReader and you can still accomplish the same thing in mostly the same way. Again, read up until you find your line, do something and then stop.

string line = null;
using (var reader in new StreamReader(filename))
{
    while ((line = reader.ReadLine()) != null)
    {
        if (line.Contains(searchTarget))
        {   // found it!
            // do something...

            break; // then stop
        }
    }
}

If you are searching for a specific pattern and not just a particular word, you'd need to use regular expressions in conjunction with this.

like image 181
Jeff Mercado Avatar answered Nov 24 '25 05:11

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!