2016-09-20 60 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

相關問題