2013-08-29 177 views
0

期待在論壇上後,我寫了這個片斷:命令行運行錯誤

public string ExecuteCmd() 
{ 
    System.Diagnostics.Process process = new System.Diagnostics.Process(); 
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
    startInfo.FileName = "cmd.exe"; 
    startInfo.Arguments = this.m_command; 
    process.StartInfo = startInfo; 
    process.Start(); 
    string output = process.StandardOutput.ReadToEnd(); 
    process.WaitForExit(); 

    return output; 
} 

m_command是一個類的成員,在構造函數初始化。 對於我的測試,它是net user。當編譯器到達這一點上,我得到以下異常:

StandardOut has not been redirected or the process hasn't started yet. 

哪裏是我的錯?

回答

1

你需要這樣的:

//.... 
startInfo.Arguments = "/C " + this.m_command; 
process.StartInfo = startInfo; 
process.StartInfo.RedirectStandardOutput = true; 
process.Start(); 
//.... 
+0

代碼工作,但輸出是錯誤的,始終不變...... http://imgur.com/0jNO6zp – Victor

+0

你與我的評論的鏈接輸出 – Victor

+0

@Victor看到我的更新。 –