2012-12-24 262 views
-1

我想運行此:C#運行命令不執行命令

string command = "echo test > test.txt"; 
System.Diagnostics.Process.Start("cmd.exe", command); 

它不工作,我究竟做錯了什麼?

+1

你是什麼意思它不工作? – ryadavilli

+1

請指定'它不工作' – Nogard

+0

什麼是真正想要做的? –

回答

12

您錯過了將/C切換爲cmd.exe以表示您要執行命令。還要注意,命令放在雙引號:

string command = "/C \"echo test > test.txt\""; 
System.Diagnostics.Process.Start("cmd.exe", command).WaitForExit(); 

如果你不希望看到的shell窗口,你可以使用以下命令:

string command = "/C \"echo test > test.txt\""; 
var psi = new ProcessStartInfo("cmd.exe") 
{ 
    Arguments = command, 
    UseShellExecute = false, 
    CreateNoWindow = true 
}; 

using (var process = Process.Start(psi)) 
{ 
    process.WaitForExit(); 
} 
+0

但他[說](http://stackoverflow.com/questions/14020664/c-sharp-run-command-not-doing-the-command/14020720#comment19362727_14020664) –

+1

@SonerGönül,是的,這就是爲什麼他應該使用我的答案中顯示的'/ C'開關。你讀過它嗎? –

0

Process類不會產生任何文件。你需要爲此使用File類。例;

string path = @"c:\temp\test.txt"; 
     if (!File.Exists(path)) 
     { 
      // Create a file to write to. 
      using (StreamWriter sw = File.CreateText(path)) 
      { 
       sw.WriteLine("Hello"); 
       sw.WriteLine("And"); 
       sw.WriteLine("Welcome"); 
      } 
     } 
+2

我不認爲他正在創建任何文件。他試圖運行一個進程並將該進程的標準輸出重定向到一個文件中。 –

+0

嗯,可能會錯過理解.. –

0

這應該有點讓你開始:

//create your command 
string cmd = string.Format(@"/c echo Hello World > mydata.txt"); 
//prepare how you want to execute cmd.exe 
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe"); 
psi.Arguments = cmd;//<<pass in your command 
//this will make echo's and any outputs accessiblen on the output stream 
psi.RedirectStandardOutput = true; 
psi.UseShellExecute = false; 
psi.CreateNoWindow = true; 
Process p = Process.Start(psi); 
//read the output our command generated 
string result = p.StandardOutput.ReadToEnd();