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

C#读取大TXT文件提取特定ID并临时存储的实现疑问

Solution to Assign Value to ram and Deduplicate Process IDs

Hey there! Let's fix your code to properly extract the Process ID, assign it to ram, and handle deduplication. Here's how to do it step by step:

First, Add the Regex Namespace

Since you're using a regular expression pattern to validate the ID format, you'll need to include this namespace at the top of your C# file:

using System.Text.RegularExpressions;

Extract and Validate the Process ID

When you hit a line containing --Process-ID=, you need three key steps:

  1. Locate the potential ID in the line
  2. Validate it against your ^\d{5}-\d{6}$ pattern to ensure it's the correct format
  3. Assign the valid ID to ram

Here's the updated, working code with these steps included:

string path = "C:\\Users\\myfile.txt", line = null, getID = null, ram = null;
string IDPattern = "^\\d{5}-\\d{6}$";

// Use 'using' block to auto-dispose the StreamReader (best practice for file handling)
using (System.IO.StreamReader file = new System.IO.StreamReader(@path))
{
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains("--Process-ID="))
        {
            // Option 1: Directly find the matching ID in the line with Regex (most robust)
            Match idMatch = Regex.Match(line, IDPattern);
            if (idMatch.Success)
            {
                ram = idMatch.Value;

                // Deduplicate logic: only print if the new ID differs from the last one
                if (getID != ram)
                {
                    getID = ram;
                    Console.WriteLine(getID);
                }
            }

            // Option 2: If ID is always immediately after "--Process-ID=", substring first then validate
            // int idStartPos = line.IndexOf("--Process-ID=") + "--Process-ID=".Length;
            // string candidateId = line.Substring(idStartPos).Trim();
            // if (Regex.IsMatch(candidateId, IDPattern))
            // {
            //     ram = candidateId;
            //     // Deduplicate logic here...
            // }
        }
    }
}

Key Details:

  • The using block ensures the StreamReader is properly closed and disposed after processing the file, preventing resource leaks.
  • Option 1 is the most reliable: it scans the entire line for your exact ID pattern, so even if there's extra text around the ID, it will still find the correct value.
  • Option 2 works if you're 100% sure the ID comes right after --Process-ID= (the Trim() handles any accidental whitespace).
  • Your deduplication logic stays intact: we only update getID and print the ID when ram holds a value different from the last stored ID.

内容的提问来源于stack exchange,提问作者user7269972

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:18:35