来自C#donds';你跑的顺序不对吗?
我有以下代码:来自C#donds';你跑的顺序不对吗?,c#,command-line,C#,Command Line,我有以下代码: using System; namespace MyProject { class Program { static void Main(string[] args) { string input = args[1]; string output = args[3]; Console.WriteLine("Finished parsing input");
using System;
namespace MyProject
{
class Program
{
static void Main(string[] args)
{
string input = args[1];
string output = args[3];
Console.WriteLine("Finished parsing input");
// runs an executable file called myexe.exe
// this exe creates an output file with the hardcoded name exeoutput.txt
string runexe = string.Format("/C myexe.exe -i {0}", input);
System.Diagnostics.Process.Start("CMD.exe", runexe);
Console.WriteLine("Finished running exe");
// moves the output created by myexe.exe to a new location
string moveOutput = string.Format("/C move exeoutput.txt {0}", output);
System.Diagnostics.Process.Start("CMD.exe", moveOutput);
Console.WriteLine("Finished moving output");
}
}
}
我使用命令MyProject.exe-I input.txt-o output.txt
运行此代码
第一次运行命令时,我得到以下输出:
Finished parsing input
Finished running exe
Finished moving output
C:\Users\me\source\repos\MyProject\MyProject\bin\Debu\netcoreapp3.1>The system cannot find the file specified
[some output from myexe.exe]
Finished parsing input
Finished running exe
Finished moving output
C:\Users\me\source\repos\MyProject\MyProject\bin\Debu\netcoreapp3.1> 1 file(s) moved.
[some output from myexe.exe]
第二次运行时,我得到以下输出:
Finished parsing input
Finished running exe
Finished moving output
C:\Users\me\source\repos\MyProject\MyProject\bin\Debu\netcoreapp3.1>The system cannot find the file specified
[some output from myexe.exe]
Finished parsing input
Finished running exe
Finished moving output
C:\Users\me\source\repos\MyProject\MyProject\bin\Debu\netcoreapp3.1> 1 file(s) moved.
[some output from myexe.exe]
看起来C代码首先执行print语句,其次执行move file命令,然后第三次执行
myexe.exe
。为什么会发生这种情况?我如何执行该命令?像这样处置流程对象
using (Process myProcess = new Process())
{
myProcess.StartInfo.UseShellExecute = false;
// You can start any process, HelloWorld is a do-nothing example.
myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
// This code assumes the process you are starting will terminate itself.
// Given that is is started without a window so you cannot terminate it
// on the desktop, it must terminate itself or you can do it programmatically
// from this application using the Kill method.
}
您是否希望C#进程等待启动的进程完成?您需要额外的代码。我认为在运行第一个CMD.EXE之后,您应该等待终止,而不是启动另一个CMD.EXE,这是一个进程。WaitForExit()此行
string runexe=string.Format(“/C myexe.EXE-I{0},input);
不会编译进程。Start
启动进程,但不会等待它完成。您需要保留对已启动进程的引用,然后调用thatProcessVariable.WaitForExit()
。我一直想知道为什么没有人在来这里提问之前查看文档。关于如何启动流程并保留对已启动流程的引用,有数千个示例,因此您可以WaitForExit。既然OP希望等待,请参见。?