You want to read a text file and count how many lines contain the word "error" (case insensitive). Which approach is best?
hard🚀 Application Q8 of 15
C Sharp (C#) - File IO
You want to read a text file and count how many lines contain the word "error" (case insensitive). Which approach is best?
AUse File.ReadAllText and check if the entire text contains "error"
BUse StreamReader.ReadLine and check each line with Contains("error") without case change
CUse File.ReadAllLines and loop checking each line with ToLower().Contains("error")
DUse StreamReader.ReadToEnd and split by spaces to count "error" words
Step-by-Step Solution
Solution:
Step 1: Understand requirement for line-by-line check
Counting lines with "error" needs checking each line separately.
Step 2: Choose case-insensitive check
Using ToLower().Contains("error") ensures case insensitivity.
Step 3: Evaluate options
File.ReadAllLines and loop checking each line with ToLower().Contains("error") reads lines and checks correctly. File.ReadAllText checks whole text, not lines. StreamReader.ReadLine without case change misses case insensitivity. StreamReader.ReadToEnd and split by spaces counts words, not lines.
Final Answer:
Use File.ReadAllLines and loop checking each line with ToLower().Contains("error") -> Option C
Quick Check:
Line-by-line + case-insensitive check = Use File.ReadAllLines and loop checking each line with ToLower().Contains("error") [OK]
Quick Trick:Read lines, convert to lower, then check Contains("error") [OK]
Common Mistakes:
MISTAKES
Ignoring case sensitivity
Checking whole text instead of lines
Splitting by spaces instead of lines
Master "File IO" in C Sharp (C#)
9 interactive learning modes - each teaches the same concept differently