2015-05-14 54 views
0

我想創建一個恢復數據庫的安裝程序,我想從cmd命令sqlcmd -L返回結果到下拉選擇按鈕單擊事件。CMD結果到一個DropDownList

是否有任何可能的方式來實現這一點,而無需將命令的輸出發送到file.txt並在之後讀取每一行?

private void button1_Click(object sender, EventArgs e) 
{ 
    string command; 
    command = "sqlcmd -L " ; 

    try 
    { 
     System.Diagnostics.ProcessStartInfo procStartInfo = 
     new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); 

     procStartInfo.RedirectStandardOutput = true; 
     procStartInfo.UseShellExecute = false; 
     procStartInfo.CreateNoWindow = false; 

     System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
     proc.StartInfo = procStartInfo; 
     proc.Start(); 

     //Get the result and populate the drop down 
    } 
    catch (Exception objException) 
    { 
     // Log the exception 
    } 
} 

回答

1

不知道這是否是你所需要的,但Process類有一個StandardOutput屬性,可以讓你獲得轉儲到由工藝標準輸出(通常是控制檯)的數據。所以這個過程結束後(使用proc.WaitForExit()爲),你可以這樣做:

string processOutput = proc.StandardOutput.ReadToEnd(); 

然後,如果你需要單獨處理的每一行,你可以這樣做:

var lines = processOutput.Split(
    new[] {Environment.NewLine}, 
    StringSplitOptions.RemoveEmptyEntries); 
foreach(var line in lines) { ... } 
+0

是的,我已經試過這但我正在尋找返回輸出到一個字符串列表中,列表中的每個元素對應於輸出的一行.Tahnks – Cosmin

+0

好的,那麼請看看編輯的答案 – Konamiman

+0

非常好,它的工作。非常感謝! – Cosmin