2016-09-20 20 views
0

我正在创建一个C#窗体窗体应用程序,它可以自动检测连接到COM端口的设备,并在标签或文本框中显示COM端口号。为了更容易的实现,我创建了一个批处理文件,它提供了有关COM端口的信息。所以我运行批处理文件并将输出存储在名为“result”的字符串中。为了验证,我使用“MessageBox.Show(result)”显示输出。接下来的一步是我想只使用标签在窗体中显示“结果”的特定行。如何仅使用C#显示批处理文件输出的特定行

结果//label1.text = 9号线//我在寻找这样的事情

我怎么能这样做?我的方法是对的吗?

这里是连接代码:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     Programming(); 
    } 

    private void Programming() 
    { 
     var processInfo = new ProcessStartInfo(@"C:\\Users\\vaka\\Desktop\\COM_Port_Detection.bat"); 
     processInfo.CreateNoWindow = true; 
     processInfo.UseShellExecute = false; 
     //processInfo.RedirectStandardError = true; 
     processInfo.RedirectStandardOutput = true; 

     using (Process process = Process.Start(processInfo)) 
     { 
      // 
      // Read in all the text from the process with the StreamReader. 
      // 
      using (StreamReader reader = process.StandardOutput) 
      { 
       string result = reader.ReadToEnd(); 
       Console.Write(result); 
       MessageBox.Show(result); 
      } 
     } 
    } 
} 
+0

}'将其删除或粘贴到声明命名空间的部分.. – MethodMan

+0

您可以使用'result.Split('\ n')'分割您的'result',并从中获取索引8:'result.Split('\ n')[8]' – Nico

+0

谢谢@heinzbeinz。错过了“.split”。将尝试一下。 – Vats

回答

0

就可以读取过程separatly返回,然后每行仅显示与9号线:为什么你有额外的`

using (StreamReader reader = process.StandardOutput) 
{ 
    var lines = new List<string>(); 
    string line; 
    while ((line = reader.ReadLine()) != null) 
     lines.Add(line); 
    Console.Write(lines[8]); 
    MessageBox.Show(lines[8]); 
} 
+0

非常感谢!它像一个魅力一样工作! :) @inwenis – Vats

0

你必须“解析”你从其他进程读取提取所需信息/行的内容。

一个简单的实现看起来是这样的:

string result = reader.ReadToEnd(); 
string[] lines = result.Split(new[] { Environment.NewLine }, StringSplitOptions.None); 
if (lines.Length >= 9) 
{ 
    Console.WriteLine(lines[8]); 
} 
else 
{ 
    // handle error 
} 
+0

这种实现方法对我的应用程序来说也很好用!非常感谢你:) @Peter我无法接受你的建议作为答案,因为网站不允许我,但展位的答案效果很好,达到了目的! – Vats

相关问题