Searching for a Specific Word in a Text File and Displaying the line its on

后端 未结 4 677
小鲜肉
小鲜肉 2020-12-31 19:13

I am having trouble attempting to find words in a text file in C#.

I want to find the word that is input into the console then display the entire line that the word

4条回答
  •  鱼传尺愫
    2020-12-31 19:47

    As mantioned by @Rinecamo, try this code:

    string toSearch = Console.ReadLine().Trim();
    

    In this codeline, you'll be able to read user input and store it in a line, then iterate for each line:

    foreach (string  line in System.IO.File.ReadAllLines(FILEPATH))
    {
        if(line.Contains(toSearch))
            Console.WriteLine(line);
    }
    

    Replace FILEPATH with the absolute or relative path, e.g. ".\file2Read.txt".

提交回复
热议问题