我想要做的是通过控制台命令窗口在C#中运行命令。 我想要这个命令做的是用我给定的输入运行一个现有的exe文件,并将输出打印到另一个文件。
我有这段代码:
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
string l_sCommand = string.Empty;
l_sCommand += "exe file" + "<" + "Input txt file" + ">" + "output txt file";
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + l_sCommand);
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
但这不起作用。 有没有人知道为什么?
答案 0 :(得分:0)
为什么不使用:
System.Diagnostics.Process.Start("<exe file>", "<args>");
您正在尝试启动cmd.exe?如果它是命令行应用程序,您可以从Process.Start
静态方法启动EXE。
答案 1 :(得分:0)
使用Process.Start
方法直接传递参数或使用内置Shell
函数
答案 2 :(得分:0)
通常,您只需将可执行文件名传递给Process.Start方法或使用Process.StartInfo属性。但是,如果要重定向标准输出,则需要将Process.StartInfo.RedirectStandardOutput设置为true,并在进程结束时读取Process.StandardOutput。请参阅以下MSDN中的示例代码提升器。
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
有关详细信息,请查看此链接中的文档。 http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
答案 3 :(得分:0)
实际上是一个常见的问题。 Process类并不像应该的那样容易使用。 (请参阅this post)如果您使用ProcessRunner class I wrote。
,以下代码将有效using CSharpTest.Net.Processes;
void Exec(string outputFile, Encoding encoding, string program, params string[] args)
{
using (TextWriter output = new StreamWriter(outputFile, false, encoding))
using (ProcessRunner pi = new ProcessRunner(program))
{
pi.OutputReceived += delegate(object sender, ProcessOutputEventArgs e)
{ output.WriteLine(e.Data); };
pi.Run(args);
}
}
答案 4 :(得分:0)
为什么不将输出流式传输到缓冲区然后自己编写呢?
public void CaptureProcess(String Command, String Arguments, String Filename)
{
// This is the code for the base process
Process myProcess = new Process();
myProcess.StartInfo = new ProcessStartInfo(Command, Arguments);
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.RedirectStandardOutput = true;
// Open a filestream for the output
using (FileStream fs = new FileStream(Filename, FileMode.OpenOrCreate))
{
using (StreamWriter sw = new StreamWriter(fs))
{
// open the stream and capture all output from the process until it dies.
using (StreamReader ProcessOutput = myProcess.StandardOutput)
{
myProcess.Start();
string output = ProcessOutput.ReadToEnd();
sw.Write(output);
myProcess.WaitForExit();
myProcess.Close();
}
}
}
}