Murali Bala
Murali Bala

Reputation: 1143

Using Linq to find the line that matches an entry

I have config file with the following format:

keydemo1,this is a demo version of the software

keyprod1,this is production version of the software

Following is the C# code to fetch the relevant line based on the key. So if I pass: GetEntryFromConfigFile ("config.ini", "keyprod1"), I am expecting the entire line below back:

"keyprod1, this is production version of the software" 

But, it is not working. Could you please let me know what I am doing wrong?

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    //var m = File.ReadLines(fileName).Where(l => l.IndexOf(entryToFind) != -1);
    //m = File.ReadLines(fileName).Where(l => l.ToLower().Contains(entryToFind.ToLower())).ToList();
    var m = File.ReadLines(fileName).Where(l => l.ToLower().IndexOf(entryToFind.ToLower()) > -1).ToList();
    //m returns 0 count;
    return m.ToString();        
}

Upvotes: 0

Views: 458

Answers (4)

w.b
w.b

Reputation: 11228

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    return File.ReadLines(filename).FirstOrDefault(line => line.ToLower().Contains(entryToFind.ToLower()));
}

Upvotes: 1

ataravati
ataravati

Reputation: 9155

Using StartsWith() or IndexOf() is not a good idea. What if you have two lines in your file starting with keydemo1 and keydemo11?

This is what I would do:

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    return File.ReadLines(filename).FirstOrDefault(line => line.Split(',')[0].Equals(entryToFind, StringComparison.CurrentCultureIgnoreCase));
}

Upvotes: 2

Robbert Brussaard
Robbert Brussaard

Reputation: 135

You can try to do the following:

  var entry = File.ReadLines(fileName).FirstOrDefault(l => l.IndexOf(entryToFind,StringComparison.CurrentCultureIgnoreCase) >= 0)

This will retrieve one entry. It will check if a line contains the given string. It ignores casing and culture settings.

Upvotes: 2

ndd
ndd

Reputation: 3071

Try this

public static string GetEntryFromConfigFile(string fileName, string entryToFind)
{
    var m = File.ReadLines(fileName).Where(l => l.StartsWith(entryToFind, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); 
    return m;
}

Upvotes: 1

Related Questions