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:
- Locate the potential ID in the line
- Validate it against your
^\d{5}-\d{6}$pattern to ensure it's the correct format - 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
usingblock ensures theStreamReaderis 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=(theTrim()handles any accidental whitespace). - Your deduplication logic stays intact: we only update
getIDand print the ID whenramholds a value different from the last stored ID.
内容的提问来源于stack exchange,提问作者user7269972
相关产品推荐
相关产品推荐

