2016-02-23 36 views
-2

我试图从C#运行命令行脚本。我希望它在没有shell的情况下运行,并将输出放入我的字符串输出中。它不喜欢p.StartInfo行。我究竟做错了什么?我没有运行像p.StartInfo.FileName =“YOURBATCHFILE.bat”的文件,如How To: Execute command line in C#, get STD OUT results。我需要设置“CMD.exe”和命令行字符串。我试过p.Start(“CMD.exe”,strCmdText);但是这给了我错误:“Memer'System.Diagnostics.Process.Start(string,string)'不能使用实例引用进行访问;请使用类型名称对其进行限定。”从没有窗口的C#运行命令行并获取输出

string ipAddress; 
    System.Diagnostics.Process p = new System.Diagnostics.Process(); 
    p.StartInfo.UseShellExecute = false; 
    p.StartInfo.RedirectStandardOutput = true; 
    string strCmdText; 
    strCmdText = "tracert -d " + ipAdress; 
    p.StartInfo("CMD.exe", strCmdText); 
    string output = p.StandardOutput.ReadToEnd(); 
    p.WaitForExit(); 
+0

你可以提供一个程序给我们建立?我99%肯定这个不会 –

+1

“它不喜欢p.StartInfo行。”究竟是什么错误? – kjbartel

+0

不,它不会运行,因为IP地址是特定于我的机器的,并且p.StartInfo也不会编译。它说它“不能像方法一样使用”。 – Sean

回答

2

此代码给我正确的输出。

const string ipAddress = "127.0.0.1"; 
Process process = new Process 
{ 
    StartInfo = 
    { 
     UseShellExecute = false, 
     RedirectStandardOutput = true, 
     RedirectStandardError = true, 
     CreateNoWindow = true, 
     FileName = "cmd.exe", 
     Arguments = "/C tracert -d " + ipAddress 
    } 
}; 
process.Start(); 
process.WaitForExit(); 
if(process.HasExited) 
{ 
    string output = process.StandardOutput.ReadToEnd(); 
} 
+0

这是我正在寻找的格式。谢谢! – Sean

+0

它给我错误“StandardOut没有被重定向或者进程​​还没有开始。” – Sean

+0

@Sean尝试编辑答案。 – ZwoRmi

1

您错误地使用了StartInfo。看看ProcessStartInfo ClassProcess.Start Method()的文档。你的代码应该是这个样子:

string ipAddress; 
System.Diagnostics.Process p = new System.Diagnostics.Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
string strCmdText; 
strCmdText = "/C tracert -d " + ipAdress; 

// Correct way to launch a process with arguments 
p.StartInfo.FileName="CMD.exe"; 
p.StartInfo.Arguments=strCmdText; 
p.Start(); 


string output = p.StandardOutput.ReadToEnd(); 
p.WaitForExit(); 

另外请注意,我说/C参数strCmdText。根据cmd /?帮助:

/C Carries out the command specified by string and then terminates. 
+0

是的,我试过了。它给了我错误“成员'System.Diagnostics.Process.Start(字符串,字符串)'不能用一个实例引用进行访问;相反,使用类型名称来限定它。” – Sean

相关问题