我想运行此: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
什么是真正想要做的? –