StreamReader统计指定内容行数异常:统计值与实际不符
Let's break down why your code isn't counting correctly—there are two critical bugs in your implementation:
You're resetting the counter every time you find a match
Yourcountvariable is declared inside theifblock. That means every time you hit a line with "Placeholder:Placeholder", you create a brand newcountvariable and set it toline.Count()(which is just the number of characters in that string, 21, not a running total). This variable gets discarded as soon as you leave theifblock, so you never track how many matches you've found overall.You're using the wrong method to increment the counter
line.Count()isn't counting matches—it's counting the length of the current line. You need to increment a counter by 1 each time you find a matching line.
Corrected Code
Here's the fixed version of your code that will properly count all matching lines:
int totalCount = 0; // Declare counter outside the loop to keep the running total using (StreamReader Reader = new StreamReader(File.Open(AccountsFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { string line; while ((line = Reader.ReadLine()) != null) { // Optional: Trim whitespace if lines might have leading/trailing spaces // string trimmedLine = line.Trim(); // if (trimmedLine == "Placeholder:Placeholder") if (line == "Placeholder:Placeholder") { totalCount++; // Increment the counter by 1 for each match } } } // After the loop, totalCount will hold the correct number of matching lines Console.WriteLine($"Total matching lines: {totalCount}");
Additional Checks to Rule Out Edge Cases
If you still don't get the expected 30 lines after fixing the code, consider these possibilities:
- Whitespace differences: Some lines might have leading/trailing spaces, tabs, or newlines. Try using
line.Trim()before comparing to eliminate this. - Case sensitivity: If the lines have different casing (e.g., "placeholder:placeholder"), use
string.Equals(line, "Placeholder:Placeholder", StringComparison.OrdinalIgnoreCase)instead of the==operator. - Partial matches: Ensure the entire line is exactly "Placeholder:Placeholder"—no extra characters before or after. If you need to check if the line contains that string instead of matching exactly, use
line.Contains("Placeholder:Placeholder").
内容的提问来源于stack exchange,提问作者YoureAllFat

