2016-12-06 21 views
-1

所以,我創建一個C#程序運行時按下按鈕命令提示符下的命令,這是當按下按鈕時執行的代碼:Process.StartInfo.FileName上來空白

private void button1_Click(object sender, EventArgs e) 
{ 
    System.Diagnostics.Process process = new System.Diagnostics.Process(); 
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized; 
    string arg = textBox1.Text + "& exit"; 
    process.StartInfo.Arguments = arg; 
    process.StartInfo.UseShellExecute = false; 
    process.StartInfo.RedirectStandardInput = true; 
    process.StartInfo.RedirectStandardOutput = true; 
    process.StartInfo.FileName = "cmd.exe"; 
    process.StartInfo = startInfo; 
    process.Start(); 
    string outp = process.StandardOutput.ReadToEnd(); 
    string error = process.StandardError.ReadToEnd(); 
    StreamWriter myStreamWriter = process.StandardInput; 
    myStreamWriter.WriteLine(textBox1.Text); 
    textBox2.Text = outp; 
    process.WaitForExit(); 
} 

也許這是明顯的,我錯過了,如果是,我很抱歉(我在C#初學者),但我不能,爲我的生活,找出爲什麼我得到一個異常拋出系統.dll的內容如下:

在System.dll中發生未處理的System.InvalidOperationException類型異常 其他信息:由於未提供文件名,無法啓動進程。

但是,我提供了一個文件名(第5行代碼片段)。任何幫助非常感謝,謝謝。 P.S. 此代碼使用:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO; 
using System.Diagnostics; 

要正常運行。

+0

我先前評論評論,要求人們把票投給了這個問題很抱歉,我只是想有一個更高的聲望,以便能夠發表評論和投票公開別人的問題了。我也認爲這是一個可以問的問題,並沒有意識到我會因爲這樣做而失去代表。 –

回答

1
process.StartInfo = startInfo; //Here problem is there, you are 
     //refreshing "process.StartInfo" with "startInfo". As "startInfo" is empty in your code. 
//So use below code 

System.Diagnostics.Process process = new System.Diagnostics.Process(); 
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized; 
string arg = textBox1.Text + "& exit"; 
startInfo.Arguments = arg; 
startInfo.UseShellExecute = false; 
startInfo.RedirectStandardInput = true; 
startInfo.RedirectStandardOutput = true; 
startInfo.FileName = "cmd.exe"; 
process.StartInfo = startInfo; 
process.Start(); 
+0

您是否需要將轉義字符添加到上面顯示的文件名中? 即「c:\\ windows \\ system32 \\ cmd.exe」 或者可能是 @「c:\ windows \ system32 \ cmd.exe」? – Monza

+0

我做了@「C」\ ...「並且cmd.exe的路徑正常並且不變 –

+0

如果將」System.Diagnostics.Process process = new System.Diagnostics.Process();「添加到頂部 –