public void Pack_Works() { string pathToNuGet = MakeAbsolute(@".nuget\NuGet.exe"); string pathToNuSpec = MakeAbsolute(@"src\app\SharpRaven\SharpRaven.nuspec"); ProcessStartInfo start = new ProcessStartInfo(pathToNuGet) { Arguments = String.Format( "Pack {0} -Version {1} -Properties Configuration=Release -Properties \"ReleaseNotes=Test\"", pathToNuSpec, typeof(IRavenClient).Assembly.GetName().Version), CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, WindowStyle = ProcessWindowStyle.Hidden, }; using (var process = new Process()) { process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data); process.StartInfo = start; Assert.That(process.Start(), Is.True, "The NuGet process couldn't start."); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(3000); Assert.That(process.ExitCode, Is.EqualTo(0), "The NuGet process exited with an unexpected code."); } }
public void ExecuteSync(string fileName, string arguments, string workingDirectory) { if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentException("fileName"); var process = new Process { StartInfo = { FileName = fileName, Arguments = arguments, WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = workingDirectory }, }; process.OutputDataReceived += Process_OutputDataReceived; process.ErrorDataReceived += Process_ErrorDataReceived; process.Exited += Process_Exited; try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } catch (Win32Exception) { throw new ExecuteFileNotFoundException(fileName); } }
public bool Execute() { var batchFile = new BatchFile(this.FileName, this.Server, this.PgDumpPath, this.Tenant); this.BatchFileName = batchFile.Create(); using (var process = new System.Diagnostics.Process()) { process.StartInfo.FileName = this.BatchFileName; process.StartInfo.CreateNoWindow = true; process.StartInfo.ErrorDialog = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.ErrorDataReceived += this.Data_Received; process.OutputDataReceived += this.Data_Received; process.Disposed += this.Completed; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); return(true); } }
public static string ExecuteCommandsSync(List <string> commands) { string result = ""; System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c "); procStartInfo.RedirectStandardOutput = true; procStartInfo.RedirectStandardError = true; procStartInfo.RedirectStandardInput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.OutputDataReceived += (s, e) => { result += e.Data; }; proc.ErrorDataReceived += (s, e) => { result += e.Data; }; proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); foreach (var command in commands) { proc.StandardInput.WriteLine(command); } proc.WaitForExit(); return(result); }
private void ProcessStart(string name, string argument, string directory) { // throw if process does not exist CheckProcess(); if (_process == null) { //directory Directory.SetCurrentDirectory(directory); OutputPaneWriteln("ProcessStart \n" + name + " " + argument + "\n in " + directory); ts.TraceInformation("ProcessStart \n" + name + " " + argument + "\n in " + directory); System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.FileName = name; process.StartInfo.Arguments = argument; process.StartInfo.WorkingDirectory = directory; process.EnableRaisingEvents = true; process.Exited += new EventHandler(this.ProcessExited); process.OutputDataReceived += new DataReceivedEventHandler(this.ProcessOutputDataReceived); process.ErrorDataReceived += new DataReceivedEventHandler(this.ProcessErrorDataReceived); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); _process = process; } else { ts.TraceData(TraceEventType.Error, 1, "Process already started"); } }
/// <summary> /// Run a bat/sh file /// </summary> /// <param name="Executable">Path to the bat/sh file</param> /// <param name="Arguments">Arguments to the bat/sh file</param> /// <param name="Tag"> /// Optional tag to write in the log before output, eg., if you pass "Build", then output will look like this: /// "Build> Output from build tool" /// </param> /// <returns>True if the process returns a 0 error code</returns> public static bool RunCommand(string Executable, string Arguments, string Tag = "") { var ProcessInfo = CreateProcessStartInfo(Executable, Arguments); ProcessInfo.CreateNoWindow = true; ProcessInfo.UseShellExecute = false; ProcessInfo.RedirectStandardError = true; ProcessInfo.RedirectStandardOutput = true; RunningProcess = System.Diagnostics.Process.Start(ProcessInfo); RunningProcess.OutputDataReceived += (object sender, DataReceivedEventArgs Evt) => Console.WriteLine(Tag + ">" + Evt.Data); RunningProcess.BeginOutputReadLine(); RunningProcess.ErrorDataReceived += (object sender, DataReceivedEventArgs Evt) => Console.WriteLine(Tag + "!>" + Evt.Data); RunningProcess.BeginErrorReadLine(); RunningProcess.WaitForExit(); int ReturnValue = RunningProcess.ExitCode; RunningProcess.Close(); RunningProcess = null; return(ReturnValue == 0); }
/// <summary> /// 运行命令 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void doCmd(object sender, DoWorkEventArgs e) { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.WorkingDirectory = @"c:\windows\system32"; p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息 p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息 p.StartInfo.RedirectStandardError = true; //重定向标准错误输出 p.StartInfo.CreateNoWindow = true; //不显示程序窗口 //Process p = CreateProcess(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe"), dir); //向cmd窗口发送输入信息 string cmdfile = e.Argument.ToString(); //p.StandardInput.WriteLine(killcmd + "\r\n"); //p.StandardInput.WriteLine(cmdfile); //p.StartInfo.Arguments = "/c " +cmdfile; p.Start();//启动程序 //p.StandardInput.WriteLine("cd /d %programfiles%\\autodesk\\maya2016\\bin"); p.StandardInput.WriteLine(cmdfile); //p.StandardInput.AutoFlush = true; p.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived); p.ErrorDataReceived += new DataReceivedEventHandler(OnErrorReceived); //p.StandardInput.WriteLine("exit\r\n"); p.BeginErrorReadLine(); p.BeginOutputReadLine(); p.WaitForExit();//等待程序执行完退出进程 p.Close(); e.Result = result; }
/// <summary> /// Executes a shell command synchronously. /// </summary> /// <param name="command">string command</param> /// <returns>string, as output of the command.</returns> public void ExecuteCommandSync(object command) { try { ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command); procStartInfo.RedirectStandardOutput = true; procStartInfo.RedirectStandardError = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.EnableRaisingEvents = true; proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived); proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); proc.Start(); proc.BeginErrorReadLine(); proc.BeginOutputReadLine(); proc.WaitForExit(); } catch (Exception objException) { } }
public static System.Diagnostics.Process Launch(string executable, string arguments, string workingDirectory) { lock (Synchronise) { var startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = !ENABLE_DEBUG_MODE; startInfo.UseShellExecute = ENABLE_DEBUG_MODE; startInfo.RedirectStandardOutput = !ENABLE_DEBUG_MODE; startInfo.RedirectStandardError = !ENABLE_DEBUG_MODE; startInfo.FileName = executable; startInfo.Arguments = arguments; startInfo.WorkingDirectory = workingDirectory; Log.Out.Info($"Command Launching: {startInfo.FileName} {startInfo.Arguments} {startInfo.WorkingDirectory}"); var process = new System.Diagnostics.Process(); process.StartInfo = startInfo; process.ErrorDataReceived += (sender, args) => Log.Out.Error(args.Data); process.OutputDataReceived += (sender, args) => Log.Out.Info(args.Data); process.EnableRaisingEvents = !ENABLE_DEBUG_MODE; process.Start(); if (!ENABLE_DEBUG_MODE) { process.BeginErrorReadLine(); process.BeginOutputReadLine(); } return(process); } }
public void Start() { if (process != null) { throw new InvalidOperationException( "VideoConverter is used once then disposed"); } if (File.Exists(OutputFileName)) { File.Delete(OutputFileName); } IssueOutputEvent(string.Format("{0} {1}", ExeName, Args)); ProcessStartInfo startInfo = new ProcessStartInfo( Path.Combine(ExecutableDir, ExeName), Args); startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; AddEnvironmentVariables(startInfo.EnvironmentVariables); process = new SProcess(); process.StartInfo = startInfo; process.ErrorDataReceived += new DataReceivedEventHandler( process_ErrorDataReceived); process.OutputDataReceived += new DataReceivedEventHandler( process_OutputDataReceived); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
static int run_process(string processname, string args) { System.Diagnostics.Process p = new System.Diagnostics.Process(); //出力とエラーをストリームに書き込むようにする p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.StandardErrorEncoding = Encoding.UTF8; p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.OutputDataReceived += (Object sender, System.Diagnostics.DataReceivedEventArgs e) => { Console.WriteLine(e.Data); }; p.ErrorDataReceived += (Object sender, System.Diagnostics.DataReceivedEventArgs e) => { Console.Error.WriteLine(e.Data); }; p.StartInfo.FileName = processname; p.StartInfo.Arguments = args; p.StartInfo.RedirectStandardInput = false; p.StartInfo.CreateNoWindow = true; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); int return_v = p.ExitCode; p.Close(); return(return_v); }
private void Run(ReceivePack rp, string hook) { var processStartInfo = new ProcessStartInfo { FileName = hook, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, WorkingDirectory = FullPath }; var appSettings = AppSettings.Current; using(var process = new Process { StartInfo = processStartInfo }) { if(!appSettings.RunHooksSilently) { process.OutputDataReceived += (d, r) => { if(!String.IsNullOrWhiteSpace(r.Data)) rp.sendMessage(r.Data); }; process.ErrorDataReceived += (d, r) => { if(!String.IsNullOrWhiteSpace(r.Data)) rp.sendError(r.Data); }; } process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); foreach(var command in rp.getAllCommands()) { process.StandardInput.WriteLine(command.getOldId().Name + " " + command.getNewId().Name + " " + command.getRefName()); } process.StandardInput.Close(); process.WaitForExit((int) appSettings.HookTimeout.TotalMilliseconds); process.WaitForExit(); process.Close(); } }
public void runCommand(StringBuilder args, bool wait = false) { //* Create your Process if (process != null && !process.HasExited) { BringProcessToFront(process); } else { process = new System.Diagnostics.Process(); process.StartInfo.FileName = Path.Combine(Settings.Default.EpicorFolder, "CustomizationEditor.exe"); process.StartInfo.Arguments = args.ToString(); process.StartInfo.WorkingDirectory = Settings.Default.EpicorFolder; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.CreateNoWindow = true; //* Set your output and error (asynchronous) handlers process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler); //* Start process and handlers process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.EnableRaisingEvents = true; process.Exited += Process_Exited; } }
public static string RunCommand(string command, string cwd) { var process = new Process { StartInfo = new ProcessStartInfo("cmd") { Arguments = "/C " + command, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, WorkingDirectory = cwd, CreateNoWindow = true } }; var output = ""; process.OutputDataReceived += delegate(object o, DataReceivedEventArgs args) { if (args.Data == null) return; output += args.Data; if (args.Data[args.Data.Length - 1] != '\n') output += '\n'; }; process.ErrorDataReceived += delegate(object o, DataReceivedEventArgs args) { output += args.Data; }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); while (!process.HasExited) Thread.Sleep(10); return output; }
public void RunShell(object sender, EventArgs e) { Console.WriteLine(String.Format("{0} {1}", this.FileName, this.Arguments)); TxtShell.AppendText("\n"); try { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = this.FileName; p.StartInfo.Arguments = this.Arguments; p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息 p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息 p.StartInfo.RedirectStandardError = true; //重定向标准错误输出 p.StartInfo.CreateNoWindow = true; //不显示程序窗口 //p.StandardInput.WriteLine("exit"); p.EnableRaisingEvents = true; p.OutputDataReceived += flushShellTxt; p.ErrorDataReceived += flushShellTxt; p.Exited += FinishProcess; p.Start();//启动程序 p.BeginOutputReadLine(); p.BeginErrorReadLine(); // p.StandardInput.AutoFlush = true; //TxtShell.Text = output; } catch (System.ComponentModel.Win32Exception) { throw new Exception("Error occurred when running command."); } }
private void ExecuteCommand(string args) { string cmdArgs = string.Format(args, "XSLT.exe", "."); cmdArgs = string.Format(" /C \"" + cmdArgs + "\""); using (Process process = new System.Diagnostics.Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = cmdArgs; process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.Start(); // To avoid deadlock on the stdout & error streams process.ErrorDataReceived += ErrorDataReceived; process.BeginErrorReadLine(); this.stdOut = process.StandardOutput.ReadToEnd(); process.WaitForExit(); this.exitCode = process.ExitCode; } this.stdErr = this.stdErrBuilder.ToString(); return; }
/// <summary> /// Compile the specified grammar /// </summary> /// <param name="grammarFile">Grammar file to compile</param> /// <param name="outputFile">The name of the binary file output</param> /// <remarks>The GOLD compiler outputs 2 versions of binary grammar tables: /// CGT and EGT. The format generated depends on the file extension of the /// output file (.cgt or .egt)</remarks> public void Compile(string grammarFile, string outputFile) { //create a helper that will classify the error messages emitted by GOLD inputFileName = grammarFile; string text = slurpFile (inputFileName); outputParser = new GoldBuildOutputParser (inputFileName); //perform an initial parse on the file. //this will get the error locations for us, //since we can't get this info from the gold compiler parser.Parse (text); //launch the GOLD command line compiler startInfo.Arguments = constructArguments (grammarFile, outputFile); startInfo.WorkingDirectory = Path.GetDirectoryName (outputFile); var p = new Process(); p.StartInfo = startInfo; p.OutputDataReceived += outputHandler; try { p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); p.Close(); } catch(Win32Exception) { var message = new CompilerMessage (MessageSeverity.Error, goldCmdPath + " was not found on path", string.Empty, 0, 0); onCompileStepComplete (message); } }
public static void limpiarTemporales() { String rutaTEMPORAL = ConfigurationManager.AppSettings["rutaTEMPORAL"].ToString(); Process borrador = new System.Diagnostics.Process(); borrador.StartInfo.FileName = "cmd.exe"; borrador.EnableRaisingEvents = true; borrador.StartInfo.CreateNoWindow = true; borrador.StartInfo.Domain = ""; borrador.StartInfo.LoadUserProfile = false; borrador.StartInfo.Password = null; borrador.StartInfo.RedirectStandardError = true; borrador.StartInfo.RedirectStandardOutput = true; borrador.StartInfo.StandardErrorEncoding = null; borrador.StartInfo.StandardOutputEncoding = null; borrador.StartInfo.UserName = ""; borrador.StartInfo.UseShellExecute = false; borrador.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; borrador.StartInfo.WorkingDirectory = "C:\\LOGOS\\TRABAJOS"; borrador.StartInfo.Arguments = "/c del /Q " + rutaTEMPORAL; Console.WriteLine(borrador.StartInfo.Arguments); borrador.Start(); borrador.BeginOutputReadLine(); borrador.BeginErrorReadLine(); borrador.WaitForExit(); borrador.Close(); borrador.Dispose(); }
private void executeCommand(string cmd) { if (string.IsNullOrWhiteSpace(txtPath.Text)) { return; } cmd = cmd.Replace("gradlew.bat", "").Replace("gradlew", ""); //disableCMD(); listOutput.Items.Clear(); Process pro = new Process(); pro.StartInfo.FileName = "cmd.exe"; pro.StartInfo.WorkingDirectory = System.IO.Directory.GetParent(txtPath.Text).FullName; pro.StartInfo.Arguments = "/C " + System.IO.Path.GetFileName(txtPath.Text) + " " + cmd; pro.StartInfo.UseShellExecute = false; pro.StartInfo.CreateNoWindow = true; pro.StartInfo.RedirectStandardOutput = true; pro.StartInfo.RedirectStandardError = true; pro.Start(); pro.BeginOutputReadLine(); pro.OutputDataReceived += (sender, e) => { if (e.Data != null) { Dispatcher.Invoke(new Action(()=> listOutput.Items.Add(e.Data))); } }; pro.BeginErrorReadLine(); pro.ErrorDataReceived += (sender, e) => { if (e.Data != null) { Dispatcher.Invoke(new Action(() => listOutput.Items.Add(e.Data))); } }; System.Threading.Tasks.Task.Factory.StartNew(pro.WaitForExit).ContinueWith(e => enableCMD()); }
public Tuple<int, string> Execute(string fileName, string arguments) { var process = new Process(); process.StartInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, }; var sb = new StringBuilder(); process.OutputDataReceived += (sender, e) => { sb.AppendLine(e.Data); }; process.ErrorDataReceived += (sender, e) => { sb.AppendLine(e.Data); }; process.Exited += (sender, e) => { }; process.EnableRaisingEvents = true; process.Start(); process.StandardInput.Dispose(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); return Tuple.Create(process.ExitCode, sb.ToString()); }
public static void Run(string testArgument, DataReceivedEventHandler dataReceived = null) { string jarArgs = String.Format("{0} {1}", JavaArgs, testArgument); var processInfo = new ProcessStartInfo(JavaExecutable, jarArgs) { CreateNoWindow = true, UseShellExecute = false, // redirected streams // redirect output stream RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true }; _process = new Process { StartInfo = processInfo, EnableRaisingEvents = true }; _process.OutputDataReceived += ProcessOnOutputDataReceived; _process.ErrorDataReceived += ProcessOnErrorDataReceived; if (dataReceived != null) { _process.OutputDataReceived += dataReceived; _process.ErrorDataReceived += dataReceived; } _process.Start(); Trace.WriteLine("Java process started."); _process.BeginOutputReadLine(); _process.BeginErrorReadLine(); Trace.WriteLine("Waiting for Java process to exit."); _process.WaitForExit(); Trace.WriteLine("Java process exited."); _process.Close(); }
private static void RunAndWait(System.Diagnostics.Process process) { process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); }
public SMTLibProcess(ProcessStartInfo psi, SMTLibProverOptions options) { this.options = options; this.smtProcessId = smtProcessIdSeq++; if (options.Inspector != null) { this.inspector = new Inspector(options); } foreach (var arg in options.SolverArguments) psi.Arguments += " " + arg; if (cancelEvent == null && CommandLineOptions.Clo.RunningBoogieFromCommandLine) { cancelEvent = new ConsoleCancelEventHandler(ControlCHandler); Console.CancelKeyPress += cancelEvent; } if (options.Verbosity >= 1) { Console.WriteLine("[SMT-{0}] Starting {1} {2}", smtProcessId, psi.FileName, psi.Arguments); } try { prover = new Process(); prover.StartInfo = psi; prover.ErrorDataReceived += prover_ErrorDataReceived; prover.OutputDataReceived += prover_OutputDataReceived; prover.Start(); toProver = prover.StandardInput; prover.BeginErrorReadLine(); prover.BeginOutputReadLine(); } catch (System.ComponentModel.Win32Exception e) { throw new ProverException(string.Format("Unable to start the process {0}: {1}", psi.FileName, e.Message)); } }
/// <summary> /// 视频格式转为Flv /// </summary> /// <param name="vFileName">原视频文件地址</param> /// <param name="ExportName">生成后的Flv文件地址</param> public bool ConvertFlv(string vFileName, string ExportName) { if ((!System.IO.File.Exists(ffmpegtool)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(vFileName)))) { return(false); } vFileName = HttpContext.Current.Server.MapPath(vFileName); ExportName = HttpContext.Current.Server.MapPath(ExportName); string Command = " -i \"" + vFileName + "\" -y -ab 32 -ar 22050 -b 800000 -s 480*360 \"" + ExportName + "\""; //Flv格式 System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = ffmpegtool; p.StartInfo.Arguments = Command; p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/tools/"); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false; p.Start(); p.BeginErrorReadLine(); p.WaitForExit(); p.Close(); p.Dispose(); return(true); }
public static void JobDelete(string printer, DataReceivedEventHandler OutputHandler = null, DataReceivedEventHandler ErrorOutputHanlder = null, System.EventHandler ProcessExit = null) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "CScript"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); process.StartInfo.RedirectStandardError = true; process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHanlder); process.StartInfo.RedirectStandardInput = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.LoadUserProfile = true; process.StartInfo.Arguments = "android.printservice.PrintService" + printer; process.EnableRaisingEvents = true; process.Exited += new System.EventHandler(ProcessExit); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
/// <summary> /// Run an executable. /// </summary> /// <param name = "executablePath">Path to the executable.</param> /// <param name = "arguments">The arguments to pass along.</param> /// <param name = "workingDirectory">The directory to use as working directory when running the executable.</param> /// <returns>A RunResults object which contains the output of the executable, plus runtime information.</returns> public static RunResults RunExecutable( string executablePath, string arguments, string workingDirectory ) { RunResults runResults = new RunResults(); if ( File.Exists( executablePath ) ) { using ( Process proc = new Process() ) { proc.StartInfo.FileName = executablePath; proc.StartInfo.Arguments = arguments; proc.StartInfo.WorkingDirectory = workingDirectory; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.OutputDataReceived += ( o, e ) => runResults.Output.Append( e.Data ).Append( Environment.NewLine ); proc.ErrorDataReceived += ( o, e ) => runResults.ErrorOutput.Append( e.Data ).Append( Environment.NewLine ); proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); runResults.ExitCode = proc.ExitCode; } } else { throw new ArgumentException( "Invalid executable path.", "executablePath" ); } return runResults; }
private void startNzbHydraProcess(bool isRestart) { process = new Process(); process.StartInfo.FileName = "nzbhydra.exe"; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.EnvironmentVariables["STARTEDBYTRAYHELPER"] = "true"; //Used to auth restart and shutdown without username and password secretAccessKey = randomString(16); process.StartInfo.EnvironmentVariables["SECRETACCESSKEY"] = secretAccessKey; if (isRestart) { process.StartInfo.Arguments = "--restarted"; writeLine("NZBHydraTray: Starting new instance of NZBHydra after a restart was requested", Color.White); } else { writeLine("NZBHydraTray: Starting new instance of NZBHydra", Color.White); } process.OutputDataReceived += OutputHandler; process.ErrorDataReceived += ErrorOutputHandler; process.EnableRaisingEvents = true; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.Exited += ProcessExited; }
public static void Run(string workingDirectory, string args) { using (Process process = new Process()) { process.StartInfo.WorkingDirectory = workingDirectory; process.StartInfo.FileName = "cmd"; process.StartInfo.Arguments = args; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += (sender, e) => { Console.WriteLine(e.Data); }; process.ErrorDataReceived += (sernder, e) => { Console.Error.WriteLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); } }
public ProcessResult Run() { var error = new StringBuilder(); var output = new StringBuilder(); var process = new Process { StartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, FileName = @"C:\Chocolatey\lib\NuGet.CommandLine.2.5.0\tools\Nuget.exe", Arguments = "foo" } }; process.ErrorDataReceived += (sender, args) => error.Append(args.Data); process.OutputDataReceived += (sender, args) => output.Append(args.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); return new ProcessResult { StandardOutput = output.ToString(), ErrorOutput = error.ToString(), ExitCode = process.ExitCode }; }
public bool Execute() { BatchFile batchFile = new BatchFile(this.FileName, this.Server, this.PgDumpPath); this.BatchFileName = batchFile.Create(); using (Process process = new Process()) { process.StartInfo.FileName = this.BatchFileName; process.StartInfo.CreateNoWindow = true; process.StartInfo.ErrorDialog = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.ErrorDataReceived += this.Data_Received; process.OutputDataReceived += this.Data_Received; process.Disposed += this.Completed; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); return true; } }
public static string Run(this ProcessStartInfo info, string logfile) { var output = new StringBuilder(); using (var process = new Process()) { process.StartInfo = info; process.OutputDataReceived += (sender, e) => output.AppendLine(e.Data); process.ErrorDataReceived += (sender, e) => output.AppendLine(e.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); using (var writer = new StreamWriter(logfile, true)) { writer.WriteLine(output.ToString()); writer.Flush(); } if (process.ExitCode != 0) { var message = string.Format( CultureInfo.InvariantCulture, "The process exited with code {0}. The output was: {1}", process.ExitCode.ToString(CultureInfo.InvariantCulture), output.ToString()); throw new InvalidOperationException(message); } } return output.ToString(); }
public static void Main(string[] args) { var psi = new ProcessStartInfo() { FileName = args[0], RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; var process = new Process() { StartInfo = psi }; process.OutputDataReceived += (sender, a) => { ProcessData(a.Data, Console.Out); }; process.ErrorDataReceived += (sender, a) => { ProcessData(a.Data, Console.Error); }; process.EnableRaisingEvents = true; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); }
public static Process StartProcessGui(string application, string args, string title, string branchName = "", OutputBox outputBox = null, OptionPageGrid options = null, string pushCommand = "") { var dialogResult = DialogResult.OK; if (!StartProcessGit("config user.name") || !StartProcessGit("config user.email")) { dialogResult = new Credentials().ShowDialog(); } if (dialogResult == DialogResult.OK) { try { var process = new Process { StartInfo = { WindowStyle = ProcessWindowStyle.Hidden, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, FileName = application, Arguments = args, WorkingDirectory = EnvHelper.SolutionDir }, EnableRaisingEvents = true }; process.Exited += process_Exited; process.OutputDataReceived += OutputDataHandler; process.ErrorDataReceived += OutputDataHandler; if (outputBox == null) { _outputBox = new OutputBox(branchName, options, pushCommand); _outputBox.Show(); } else { _outputBox = outputBox; } process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); _outputBox.Text = title; _outputBox.Show(); return(process); } catch (Exception e) { MessageBox.Show(e.Message, $"{application} not found", MessageBoxButtons.OK, MessageBoxIcon.Error); } } return(null); }
public static void openFeeddownload(string torrentclient, string folder, string link) { var sta = new Process(); var downloadsafe = folder.Trim(); Debug.Write(downloadsafe); //"add -p 'D:/Program Files (x86)/Deluge' 'D:/Development/python34/Anime checker/torrents/[HorribleSubs] Hibike! Euphonium - 13 [720p].mkv.torrent'" var call = $"\"add -p '{downloadsafe}' '{link.Replace("https", "http")}'\""; call = call.Replace(@"\\", "/"); call = call.Replace(@"\", "/"); sta.StartInfo.FileName = torrentclient; sta.StartInfo.Arguments = call; sta.StartInfo.RedirectStandardOutput = true; sta.StartInfo.RedirectStandardError = true; sta.EnableRaisingEvents = true; sta.StartInfo.CreateNoWindow = true; // see below for output handler sta.ErrorDataReceived += proc_DataReceived; sta.OutputDataReceived += proc_DataReceived; sta.StartInfo.UseShellExecute = false; sta.Start(); sta.BeginErrorReadLine(); sta.BeginOutputReadLine(); sta.WaitForExit(); }
public LaunchCommandAsProcess(string workingdirectory) { p = new Process { StartInfo = { FileName = @"C:\Windows\System32\cmd.exe", UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; if (!string.IsNullOrEmpty(workingdirectory)) p.StartInfo.WorkingDirectory = workingdirectory; p.Start(); stdIn = p.StandardInput; p.OutputDataReceived += Process_OutputDataReceived; p.ErrorDataReceived += Process_OutputDataReceived; p.BeginOutputReadLine(); p.BeginErrorReadLine(); }
public static void Execute(string command, EventHandler endedHandler = null) { if (!IsGitInstalled) { Debug.LogError("GIT is not installed on this system, Please install git"); return; } Process process = new System.Diagnostics.Process(); ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.CreateNoWindow = true; startInfo.FileName = "git"; startInfo.Arguments = command; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; process.OutputDataReceived += (sender, args) => { UPMConsole.Log(args.Data); }; process.ErrorDataReceived += (sender, args) => { UPMConsole.Log(args.Data); }; if (endedHandler != null) { process.Exited += endedHandler; } process.StartInfo = startInfo; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
private void materialFlatButton4_Click(object sender, EventArgs e) { using (Process process = new System.Diagnostics.Process()) { if (Environment.OSVersion.Platform == PlatformID.Win32NT) { process.StartInfo.FileName = Environment.CurrentDirectory + "/tools/mp4box.exe"; } else { process.StartInfo.FileName = "mp4box"; } process.StartInfo.Arguments = "-version"; // 禁用操作系统外壳程序 process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; //输出开启 process.StartInfo.RedirectStandardError = true; string output = ""; process.OutputDataReceived += new DataReceivedEventHandler((s, e) => { output += e.Data + "\r\n"; }); process.ErrorDataReceived += new DataReceivedEventHandler((s, e) => { output += e.Data + "\r\n"; }); process.Start(); //启动进程 process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(2000); MessageBox.Show(output); } }
public static void Install() { string filename = GetOsDependantFilename(); var startInfo = new ProcessStartInfo(filename, InstallArgs) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = Path.GetTempPath() }; using (var process = new Process()) { var output = new StringBuilder(); process.StartInfo = startInfo; process.OutputDataReceived += (sender, e) => { if (e.Data != null) output.AppendLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); ParseForElevatedPermissionsError(output.ToString()); Console.Out.WriteLine(output.ToString()); } }
int Execute(System.Diagnostics.Process process, string input) { try { process.Start(); // read from stdout if (process.StartInfo.RedirectStandardOutput) { process.BeginOutputReadLine(); } // read from stderr if (process.StartInfo.RedirectStandardError) { process.BeginErrorReadLine(); } // write to stdin if (process.StartInfo.RedirectStandardInput) { process.StandardInput.WriteLine(input); process.StandardInput.Flush(); process.StandardInput.Close(); } process.WaitForExit(); } catch (Exception e) { throw new IOException($"failed to execute: {process.StartInfo.FileName} {process.StartInfo.Arguments}", e); } return(process.ExitCode); }
public static void ExecuteCommand(ExecutableInfo _info) { Debug.WriteLine($"Execucting: {_info.Command}"); //var processInfo = new ProcessStartInfo("cmd.exe", "/c " + _info.Command); var processInfo = new ProcessStartInfo("openvpn.exe", _info.Command); //processInfo.WorkingDirectory = _info.WorkingDirectory; processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardError = true; processInfo.RedirectStandardOutput = true; Process process = new Process(); process.StartInfo = processInfo; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine(e.Data); process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine(e.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); }
private bool BuildSolution(string solutionFilePath, string buildArguments) { var result = true; string output = String.Empty; string errorOutput = String.Empty; ProcessStartInfo processStartInfo = new ProcessStartInfo(net4MSBuildPath, string.Join(" ", buildArguments, solutionFilePath)); processStartInfo.UseShellExecute = false; processStartInfo.ErrorDialog = false; processStartInfo.RedirectStandardError = true; processStartInfo.RedirectStandardInput = true; processStartInfo.RedirectStandardOutput = true; System.Diagnostics.Process process = new System.Diagnostics.Process(); process.EnableRaisingEvents = true; process.StartInfo = processStartInfo; process.OutputDataReceived += (sender, args1) => output += args1.Data; process.ErrorDataReceived += (sender, args2) => errorOutput += args2.Data; bool processStarted = process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); if (!String.IsNullOrEmpty(errorOutput) || !String.IsNullOrEmpty(output)) { result = false; notificationService.Notify("Build Failed", errorOutput + Environment.NewLine + output, NotificationType.Error); } return result; }
protected override void OnStart(string[] args) { var syslog = Syslog.Build(Config.Params(), eventSource); process = new Process { StartInfo = { FileName = "garden-windows.exe", Arguments = "--listenNetwork=tcp -listenAddr=0.0.0.0:9241 -containerGraceTime=5m -containerizerURL=http://localhost:1788", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, } }; process.EnableRaisingEvents = true; process.Exited += process_Exited; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Information, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Informational); }; process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Warning, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Warning); }; EventLog.WriteEntry(eventSource, "Starting", EventLogEntryType.Information, 0); EventLog.WriteEntry(eventSource, ("Syslog is " + (syslog==null ? "NULL" : "ALIVE")), EventLogEntryType.Information, 0); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
private void btnUpload_Click(object sender, EventArgs e) { string avrPath = @".\avrdude\"; string com = Properties.Settings.Default.portName; string baud = Properties.Settings.Default.baudRate.ToString(); using (System.Diagnostics.Process pProcess = new System.Diagnostics.Process()) { pProcess.StartInfo.FileName = avrPath + "avrdude.exe"; pProcess.StartInfo.Arguments = "-C" + avrPath + "avrdude.conf" + " " + "-v -patmega2560 -cwiring -P" + com + " -b" + baud + " -D" + " " + "-Uflash:w:" + filePath + ":i"; //pProcess.StartInfo.Arguments = "-?"; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.RedirectStandardError = true; pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; pProcess.StartInfo.CreateNoWindow = true; //not diplay a windows pProcess.OutputDataReceived += new DataReceivedEventHandler(sortOutputHandler); pProcess.ErrorDataReceived += new DataReceivedEventHandler(sortOutputHandler); pProcess.Start(); pProcess.BeginOutputReadLine(); pProcess.BeginErrorReadLine(); while (!pProcess.HasExited) { Application.DoEvents(); // This keeps your form responsive by processing events } } Console.WriteLine("AVRDUDE finished"); }
public void run() { if (!File.Exists(exe)) return; list.Add(this); process = new Process(); try { process.EnableRaisingEvents = true; process.Exited += new EventHandler(runFinsihed); process.StartInfo.FileName = Main.IsMono ? exe : wrapQuotes(exe); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += new DataReceivedEventHandler(OutputDataHandler); process.StartInfo.RedirectStandardError = true; process.ErrorDataReceived += new DataReceivedEventHandler(OutputDataHandler); process.StartInfo.Arguments = arguments; process.Start(); // Start the asynchronous read of the standard output stream. process.BeginOutputReadLine(); process.BeginErrorReadLine(); } catch (Exception e) { Main.conn.log(e.ToString(), false, 2); list.Remove(this); } }
/// <summary> /// 从视频中截取一帧 /// </summary> public static void GetOneFrameImageFromVideo(string videoPath, string thumbnailPath, Action callback) { using (System.Diagnostics.Process ffmpeg = CreateProcess(FFmpegPath)) { string tempVideoPath = string.Format("\"{0}\"", videoPath); ffmpeg.StartInfo.Arguments = " -i " + tempVideoPath + " -q:v 2 -f image2 " + thumbnailPath; ffmpeg.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e) { if (System.IO.File.Exists(thumbnailPath)) { callback?.Invoke(); } }); ffmpeg.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e) { if (System.IO.File.Exists(thumbnailPath)) { callback?.Invoke(); } }); ffmpeg.Start(); ffmpeg.BeginErrorReadLine(); ffmpeg.BeginOutputReadLine(); } }
private Tuple <int, bool, string> InvokeProcess(System.Diagnostics.Process process, DataReceivedEventHandler processOnOutputDataReceived) { process.OutputDataReceived += processOnOutputDataReceived; var errorsBuilder = new StringBuilder(); var errors = false; process.ErrorDataReceived += (s, a) => { if (string.IsNullOrEmpty(a.Data)) { return; } errorsBuilder.AppendLine(a.Data); errors = true; processOnOutputDataReceived(s, a); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); var exitCode = process.ExitCode; process.OutputDataReceived -= processOnOutputDataReceived; process.ErrorDataReceived -= processOnOutputDataReceived; process.Close(); return(Tuple.Create(exitCode, errors, errorsBuilder.ToString())); }
private void run_button_Click(object sender, EventArgs e) { if (selectedCode == "C#") { string cmd = "/C output.exe"; System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.WorkingDirectory = path; proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.Arguments = cmd; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.Start(); proc.OutputDataReceived += (object senderr, DataReceivedEventArgs ee) => MessageBox.Show(ee.Data, "Outputs"); proc.BeginOutputReadLine(); proc.ErrorDataReceived += (object senderr, DataReceivedEventArgs ee) => MessageBox.Show(ee.Data, "Errors"); proc.BeginErrorReadLine(); proc.WaitForExit(); Console.WriteLine("ExitCode: {0}", proc.ExitCode); proc.Close(); } }
public static void Start(string fileName, string arguments = null, string workingDirectory = null) { var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, WorkingDirectory = workingDirectory, UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true }; using (var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }) { process.ErrorDataReceived += Log; process.OutputDataReceived += Log; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); } }
protected override void OnStart(string[] args) { WriteConfigFile(); process = new Process { StartInfo = { FileName = "metron.exe", Arguments = @"--config=metron\config.json", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory } }; process.EnableRaisingEvents = true; process.Exited += process_Exited; var syslog = Syslog.Build(Config.Params(), eventSource); process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Information, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Informational); }; process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Warning, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Warning); }; EventLog.WriteEntry(eventSource, "Starting", EventLogEntryType.Information, 0); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
public static AsyncProcess Start(ProcessStartInfo startInfo, IDictionary environment) { startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; if (environment != null) { foreach (var i in environment.Keys) { startInfo.EnvironmentVariables[(string)i] = (string)environment[i]; } } var process = new Process { StartInfo = startInfo }; var result = new AsyncProcess(process); process.EnableRaisingEvents = true; // set up std* access process.ErrorDataReceived += (sender, args) => result._stdError.Add(args.Data); process.OutputDataReceived += (sender, args) => result._stdOut.Add(args.Data); process.Exited += (sender, args) => { result._stdError.Completed(); result._stdOut.Completed(); }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); return result; }
private Process ExecuteCore(string file, string arguments) { if (string.IsNullOrEmpty(file)) throw new ArgumentNullException("file"); _messages.Write(string.Format("Starting {0} {1}\n", file, arguments)); System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo() { UseShellExecute = false, WorkingDirectory = _basePath, CreateNoWindow = true, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, FileName = Path.Combine(_basePath, file), Arguments = arguments, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, }; var process = new System.Diagnostics.Process(); process.StartInfo = psi; process.OutputDataReceived += (s, e) => _syncCtx.Post(state => { _messages.WriteLine(e.Data); }, null); process.ErrorDataReceived += (s, e) => _syncCtx.Post(state => { _messages.WriteLine(e.Data); }, null); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); return process; }
public static void JobDelete(string printer, DataReceivedEventHandler OutputHandler = null, DataReceivedEventHandler ErrorOutputHanlder = null, System.EventHandler ProcessExit = null) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "CScript"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); process.StartInfo.RedirectStandardError = true; process.ErrorDataReceived += new DataReceivedEventHandler(ErrorOutputHanlder); process.StartInfo.RedirectStandardInput = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.LoadUserProfile = true; process.StartInfo.Arguments = "-E:vbscript C:/Windows/System32/Printing_Admin_Scripts/ja-JP/prnqctl.vbs -p " + printer + " -x"; process.EnableRaisingEvents = true; process.Exited += new System.EventHandler(ProcessExit); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
/// <summary> /// Not Completely Implemented /// </summary> /// <param name="processPath"></param> /// <param name="processArguments"></param> /// <param name="startProcess"></param> /// <param name="waitForExit"></param> /// <param name="processDataCapturer"></param> /// <returns></returns> public static Process LaunchExternalProcess(string processPath, string processArguments, bool startProcess, bool waitForExit, IProcessDataCapturer processDataCapturer) { var externalProcess = new Process(); var externalProcessStartInfo = new ProcessStartInfo { Arguments = processArguments, FileName = processPath, RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false }; externalProcess.StartInfo = externalProcessStartInfo; if (processDataCapturer != null) { processDataCapturer.Process = externalProcess; } if (startProcess) { externalProcess.Start(); } if (processDataCapturer != null && startProcess) { externalProcess.BeginOutputReadLine(); externalProcess.BeginErrorReadLine(); } if (waitForExit) externalProcess.WaitForExit(); return externalProcess; }
/// <summary> /// Executes process and capture its output. /// </summary> /// <param name="processStartInfo">The process start information.</param> /// <param name="output">The output.</param> /// <returns></returns> public static Process ExecuteAndCaptureOutput(ProcessStartInfo processStartInfo, out string output) { processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; var process = new Process { StartInfo = processStartInfo }; var outputBuilder = new StringBuilder(); process.OutputDataReceived += (sender, args) => { lock (outputBuilder) { if (args.Data != null) outputBuilder.AppendLine(args.Data); } }; process.ErrorDataReceived += (sender, args) => { lock (outputBuilder) { if (args.Data != null) outputBuilder.AppendLine(args.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); output = outputBuilder.ToString(); return process; }
public CmdResult Run() { Process proc = new Process(); proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.Arguments = "/c " + _command; if(!string.IsNullOrEmpty(_runFrom)) proc.StartInfo.WorkingDirectory = _runFrom; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived); WriteLog(_command); proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); var result = new CmdResult(_command, proc.ExitCode, _output.ToString()); proc.Close(); WriteLog("exit code: " + result.ExitCode); return result; }
public ConsoleDataHandler(System.Diagnostics.Process p) { p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(HandleOutputDataReceived); p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(HandleErrorDataReceived); p.BeginErrorReadLine(); p.BeginOutputReadLine(); }
private static void ForwardOutput(System.Diagnostics.Process process, IOutputForwarder forwarder) { process.OutputDataReceived += (_, data) => forwarder.WriteOutputLine(data.Data); process.ErrorDataReceived += (_, data) => forwarder.WriteErrorLine(data.Data); process.BeginErrorReadLine(); process.BeginOutputReadLine(); }
public bool ExecuteCommand(string filename, string arguments, string workingDirectory, bool wait = true) { bool result = true; try { log.Info("ExecuteCommand:" + filename + " " + arguments); using (System.Diagnostics.Process process = new System.Diagnostics.Process()) { process.StartInfo.FileName = filename; process.StartInfo.Arguments = arguments; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.UseShellExecute = false; if (workingDirectory != null) { process.StartInfo.WorkingDirectory = workingDirectory; } process.StartInfo.CreateNoWindow = true; process.OutputDataReceived += (sender, e) => { if (e.Data != null) { //if (filename != YARNCmd) { log.Info(e.Data); } } }; process.ErrorDataReceived += (sender, e) => { if (e.Data != null) { //if (filename != YARNCmd) { log.Info(e.Data); } } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (wait) { process.WaitForExit(); } } } catch (Exception ex) { result = false; throw ex; } return(result); }
private async Task <string> Exec(string exe, string args) { var sb = new StringBuilder(); var startinfo = new ProcessStartInfo(exe, args) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = _workingDirectory }; var ret = new Process { StartInfo = startinfo, EnableRaisingEvents = true }; ret.OutputDataReceived += (sender, eventArgs) => { lock (sblock) { var data = eventArgs.Data; if (string.IsNullOrEmpty(data)) { return; } sb.AppendLine(data); Debug.Write(data); } }; ret.ErrorDataReceived += (sender, eventArgs) => { lock (sblock) { var data = eventArgs.Data; if (string.IsNullOrWhiteSpace(data)) { return; } sb.AppendLine("ERROR: " + data); Debug.Write(data); } }; Debug.Assert(ret != null, "ret != null"); if (_logger != null) { _logger.LogInfo("» git " + args); } ret.Start(); ret.BeginOutputReadLine(); ret.BeginErrorReadLine(); await ret.WaitForExitAsync(); lock (sblock) { return(sb.ToString()); } }
/// <summary> /// Java コマンド実行 /// </summary> /// <param name="iPath">対象ファイルパス</param> /// <returns>エラーまたは警告があればFALSE、それ以外はTRUE</returns> public bool Do(string iPath) { this.OutputStandard.Clear(); this.OutputError.Clear(); try { System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo { StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false), UseShellExecute = false, CreateNoWindow = true, FileName = ExePath, RedirectStandardOutput = true, RedirectStandardError = true }; psi.Arguments = string.Format(" \"{0}\" -verbose", iPath); using (System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi)) { // OutputDataReceivedとErrorDataReceivedイベントハンドラを追加 p.OutputDataReceived += this.P_OutputDataReceived; p.ErrorDataReceived += this.P_ErrorDataReceived; try { // 非同期で出力とエラーの読み取りを開始 p.BeginOutputReadLine(); p.BeginErrorReadLine(); } catch { this.OutputError.Add("結果取得に 失敗 @DoKindlegenFor"); Console.WriteLine(@"結果取得に 失敗"); } // WaitForExitはReadToEndの後である必要がある (親プロセス、子プロセスでブロック防止のため) p.WaitForExit(); this.StatusCode = p.ExitCode; } } catch (Exception ex_psi) { this.OutputError.Clear(); this.OutputError.Add("java コマンド 失敗 @DoKindlegenFor"); Console.WriteLine(@"java コマンド 失敗"); Console.WriteLine(ex_psi.ToString()); return(false); } return(true); }