-2

I'm trying to not hardcode my tokens into my program but I can't figure out how to look for a specific line with a certain word from a text file.

My current code is:

System.IO.File.ReadAllLines(@"C:\INPUTFILE.txt")

How can I modify this to find the line that starts with "CERTAINWORD", or give me a null if it doesn't?

2 Answers2

0

You write

var line = System.IO.File.ReadLines(@"C:\INPUTFILE.txt")
                         .FirstOrDefault(x => x.StartsWith("CERTAINWORD"));
if(line == null)
    Console.WriteLine("Not found");

You use the ReadLines method instead of ReadAllLines. This allows you to enumerate each line while you read them. Each line then is passed to the FirstOrDefault to check if it starts with the requested value. If a line matches the request then the enumaration is stopped and the line is returned, if no line matches the result is null.

Steve
  • 213,761
  • 22
  • 232
  • 286
0

You could do something like this.

foreach (string line in File.ReadLines(@"C:\INPUTFILE.txt"))
{
    if (line.Contains("CERTAINWORD"))
    {
        Console.WriteLine(line);
    }
}
thesystem
  • 554
  • 1
  • 10
  • 31