Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text from a text file with specific pattern

Tags:

c#

Hi there I have a requirement where i need to read content from a text file. The sample text content is as below.

Name=Check_Amt
Public=Yes
DateName=pp
Name=DBO

I need to read the text and only extract the value which comes after Name='What ever text'.

So I am expecting the output as Check_Amt, DBO

I need to do this in C#

like image 867
Umesh Kumar Avatar asked Mar 21 '26 00:03

Umesh Kumar


1 Answers

When querying data (e.g. file lines) Linq is often a convenient tool; if the file has lines in

name=value

format, you can query it like this

  1. Read file lines
  2. Split each line into name, value pair
  3. Filter pairs by their names
  4. Extract value from each pair
  5. Materialize values into a collection

Code:

using System.Linq;

...

// string[] {"Check_Amt", "DBO"}
var values = File 
  .ReadLines(@"c:\MyFile.txt")
  .Select(line => line.Split(new char[] { '=' }, 2)) // split into name, value pairs
  .Where(items => items.Length == 2)                 // to be on the safe side
  .Where(items => items[0] == "Name")                // name == "Name" only
  .Select(items => items[1])                         // value from name=value
  .ToArray();                                        // let's have an array

finally, if you want comma separated string, Join the values:

// "Check_Amt,DBO"
string result = string.Join(",", values);
like image 129
Dmitry Bychenko Avatar answered Mar 23 '26 12:03

Dmitry Bychenko



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!