我想運行此:C#運行命令不執行命令
string command = "echo test > test.txt";
System.Diagnostics.Process.Start("cmd.exe", command);
它不工作,我究竟做錯了什麼?
我想運行此:C#運行命令不執行命令
string command = "echo test > test.txt";
System.Diagnostics.Process.Start("cmd.exe", command);
它不工作,我究竟做錯了什麼?
您錯過了將/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();
}
但他[說](http://stackoverflow.com/questions/14020664/c-sharp-run-command-not-doing-the-command/14020720#comment19362727_14020664) –
@SonerGönül,是的,這就是爲什麼他應該使用我的答案中顯示的'/ C'開關。你讀過它嗎? –
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");
}
}
我不認爲他正在創建任何文件。他試圖運行一個進程並將該進程的標準輸出重定向到一個文件中。 –
嗯,可能會錯過理解.. –
這應該有點讓你開始:
//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();
你是什麼意思它不工作? – ryadavilli
請指定'它不工作' – Nogard
什麼是真正想要做的? –