2013-08-29 179 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看到我的更新。 –