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

后端 未结 4 692
小鲜肉
小鲜肉 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:38

    Iterate through all the lines (StreamReader, File.ReadAllLines, etc.) and check if line.Contains("December") (replace "December" with the user input).

    Edit: I would go with the StreamReader in case you have large files. And use the IndexOf-Example from @Matias Cicero instead of contains for case insensitive.

    Console.Write("Keyword: ");
    var keyword = Console.ReadLine() ?? "";
    using (var sr = new StreamReader("")) {
        while (!sr.EndOfStream) {
            var line = sr.ReadLine();
            if (String.IsNullOrEmpty(line)) continue;
            if (line.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase) >= 0) {
                Console.WriteLine(line);
            }
        }
    }
    

提交回复
热议问题