C#如何拆分CMD执行输出结果存入变量,匹配内容后写入RichTextBox
C# 拆分ipconfig命令输出并插入RichTextBox实现代码
核心实现逻辑:
- 优化输出读取逻辑,用StringBuilder缓存输出避免界面卡顿
- 支持按关键字匹配你需要的字段,也支持按网卡块拆分完整内容
- 可自定义匹配内容的显示格式(比如高亮、加粗)
using System.Text; using System.Diagnostics; using System.Drawing; private void NetWorkCheker_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // 先清空原有内容 Result.Clear(); // 定义需要匹配提取的字段关键字,可根据实际需求增删 var targetFields = new List<string> { "物理地址", "IPv4 地址", "子网掩码", "默认网关", "DNS 服务器" }; var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "cmd.exe", Arguments = "/c ipconfig /all", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, StandardOutputEncoding = Encoding.GetEncoding("GBK") // 解决中文系统下cmd输出乱码问题 } }; proc.Start(); StringBuilder outputBuilder = new StringBuilder(); // 逐行读取输出的同时做匹配处理 while (!proc.StandardOutput.EndOfStream) { string currentLine = proc.StandardOutput.ReadLine(); outputBuilder.AppendLine(currentLine); if (!string.IsNullOrWhiteSpace(currentLine)) { // 逻辑1:识别网卡块,插入分区标题(可选) if (currentLine.Contains("适配器") && currentLine.EndsWith(":")) { Result.SelectionFont = new Font(Result.Font, FontStyle.Bold); Result.SelectionColor = Color.Blue; Result.AppendText(Environment.NewLine + "=== " + currentLine.TrimEnd(':') + " ===" + Environment.NewLine); Result.SelectionFont = new Font(Result.Font, FontStyle.Regular); Result.SelectionColor = Color.Black; } // 逻辑2:匹配目标字段,高亮展示字段名 foreach (var field in targetFields) { if (currentLine.Contains(field)) { Result.SelectionColor = Color.Red; Result.AppendText(field + ":"); Result.SelectionColor = Color.Black; // 提取字段对应的值,去掉多余空格和标记 string value = currentLine.Split(new[] { ':' }, 2)[1].Trim().Replace("(首选)", ""); Result.AppendText(value + Environment.NewLine); break; } } } } proc.WaitForExit(); proc.Dispose(); // 完整原始输出存储在该变量中,可按需使用 string fullRawOutput = outputBuilder.ToString(); }
说明:如果需要其他自定义拆分规则,直接在逐行读取的循环中新增判断逻辑即可,不需要等全部输出完成后再统一拆分,逐行处理的性能和灵活性更高。
内容的提问来源于stack exchange,提问作者AbuRajih
相关产品推荐
相关产品推荐

