2016-02-23 38 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

相關問題