我正在尝试执行多个命令,而不是每次都创建一个新进程.基本上,我想启动DOS命令shell,切换到MySQL命令shell,然后执行命令.这是我如何调用该过程(也在下面).另外,我如何处理命令中的"\"?
ExecuteCommand("mysql --user=root --password=sa casemanager", 100, false); ExecuteCommand(@"\. " + Environment.CurrentDirectory + @"\MySQL\CaseManager.sql", 100, true); private void ExecuteCommand(string Command, int Timeout, Boolean closeProcess) { ProcessStartInfo ProcessInfo; Process Process; ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command); ProcessInfo.CreateNoWindow = false; ProcessInfo.UseShellExecute = false; Process = Process.Start(ProcessInfo); Process.WaitForExit(Timeout); if (closeProcess == true) { Process.Close(); } }
scottm.. 76
您可以重定向标准输入并使用StreamWriter写入它:
Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.UseShellExecute = false; p.StartInfo = info; p.Start(); using (StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine("mysql -u root -p"); sw.WriteLine("mypassword"); sw.WriteLine("use mydb;"); } }
对我来说很好.也许这可以标记为答案? (3认同)
Filip.. 44
const string strCmdText = "/C command1&command2"; Process.Start("CMD.exe", strCmdText);
M4N.. 12
难道你不能只将所有命令写入临时文件夹中的.cmd文件,然后执行该文件吗?
您可以重定向标准输入并使用StreamWriter写入它:
Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.UseShellExecute = false; p.StartInfo = info; p.Start(); using (StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine("mysql -u root -p"); sw.WriteLine("mypassword"); sw.WriteLine("use mydb;"); } }
const string strCmdText = "/C command1&command2"; Process.Start("CMD.exe", strCmdText);
难道你不能只将所有命令写入临时文件夹中的.cmd文件,然后执行该文件吗?
ProcessStartInfo pStartInfo = new ProcessStartInfo(); pStartInfo.FileName = "CMD"; pStartInfo.Arguments = @"/C mysql --user=root --password=sa casemanager && \. " + Environment.CurrentDirectory + @"\MySQL\CaseManager.sql" pStartInfo.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(pStartInfo);
该&&
是告诉命令shell,还有另一种命令来执行的方式。
另一个答案暗示在较新版本的Windows下,似乎有必要读取标准输出和/或标准错误流,否则它将在命令之间停滞。这样做而不是使用延迟的更整洁的方法是使用异步回调来消耗流的输出:
static void RunCommands(Listcmds, string workingDirectory = "") { var process = new Process(); var psi = new ProcessStartInfo(); psi.FileName = "cmd.exe"; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.UseShellExecute = false; psi.WorkingDirectory = workingDirectory; process.StartInfo = psi; process.Start(); process.OutputDataReceived += (sender, e) => { Console.WriteLine(e.Data); }; process.ErrorDataReceived += (sender, e) => { Console.WriteLine(e.Data); }; process.BeginOutputReadLine(); process.BeginErrorReadLine(); using (StreamWriter sw = process.StandardInput) { foreach (var cmd in cmds) { sw.WriteLine (cmd); } } process.WaitForExit(); }