You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

StreamReader统计指定内容行数异常:统计值与实际不符

Fixing Your Line Counting Issue

Let's break down why your code isn't counting correctly—there are two critical bugs in your implementation:

  1. You're resetting the counter every time you find a match
    Your count variable is declared inside the if block. That means every time you hit a line with "Placeholder:Placeholder", you create a brand new count variable and set it to line.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 the if block, so you never track how many matches you've found overall.

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:31:11