我正在尝试从本地文件夹运行cmd,并希望同时传递多个命令,例如:一旦我能够运行此命令,p.StandardInput.WriteLine(“ multichain-util create chain34”);执行完此操作后,我想传递此命令p.StandardInput.WriteLine(“ multichai-cli chain 34 -daemon”)
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.WorkingDirectory = @"D:\multichain-windows-2.0.2";
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.StandardInput.WriteLine("multichain-util create chain34");
p.StandardInput.Flush();
p.StandardInput.Close();
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd());
Console.ReadKey();
}
}
答案 0 :(得分:0)
将所有与流程相关的内容移至方法中。将命令列表作为该命令的参数。然后,代替一个p.StandardInput.WriteLine()
,遍历命令列表并将其全部写入。
static void Main()
{
var commands = new List<string>() { "dir", "mkdir ABC", "dir" };
ExecuteCmd(commands);
Console.ReadLine();
}
static void ExecuteCmd(List<string> commands)
{
Process p = new Process();
p.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
foreach (var comm in commands)
p.StandardInput.WriteLine(comm);
p.StandardInput.Flush();
p.StandardInput.Close();
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd());
}