void Button1Click(object sender, EventArgs e) { Process myProcess = new Process(); ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(@"C:\Users\IJMAIL\AppData\Roaming\Nox\bin\nox_adb.exe" ); myProcessStartInfo.Arguments = "devices"; myProcessStartInfo.UseShellExecute = false; myProcessStartInfo.RedirectStandardOutput = true; // 데이터 받기 myProcessStartInfo.RedirectStandardError = true; // 오류내용 받기 myProcessStartInfo.CreateNoWindow = true; // 원도우창 띄우기(true 띄우지 않기, false 띄우기) myProcess.StartInfo = myProcessStartInfo; myProcess.Start(); myProcess.WaitForExit(); //string output = myProcess.StandardOutput.ReadToEnd(); string output = myProcess.StandardOutput.ReadToEnd(); string error = myProcess.StandardError.ReadToEnd(); string[] aa = output.Split('\n'); for(int i=1; i<aa.Length; i++) { listBox1.Items.Add(aa[i]); } //listBox1.Items.Add(aa.Length); //listBox1.Items.Add(aa[1]); //listBox1.Text = output; // 프로그램이 종료되면 //System.Console.WriteLine( "ExitCode is " + myProcess.ExitCode ); myProcess.WaitForExit(); myProcess.Close(); }
/// <summary> /// 解压缩 /// </summary> /// <param name="zipname">要解压的文件名</param> /// <param name="zippath">要解压的文件路径</param> public static void DeZip(string zipname, string zippath) { try { the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command"); the_Obj = the_Reg.GetValue(""); the_rar = the_Obj.ToString(); the_Reg.Close(); the_rar = the_rar.Substring(1, the_rar.Length - 7); the_Info = " X " + zipname + " " + zippath; the_StartInfo = new ProcessStartInfo(); the_StartInfo.FileName = the_rar; the_StartInfo.Arguments = the_Info; the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; the_Process = new Process(); the_Process.StartInfo = the_StartInfo; the_Process.Start(); the_Process.WaitForExit(); the_Process.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } }
public bool Convert(string input, string outputName) { try { Console.WriteLine("input:" + input); Console.WriteLine("outputName:" + outputName); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "BabylonExport.exe"; p.StartInfo.Arguments = "/i:" + input + " /o:" + outputName; p.Start(); if (p.WaitForExit(1000 * 60 * 3)) { p.Close(); return true; } else { p.Close(); return false; } } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } }
/// <summary> /// Preprocesses and runs Mike She /// Note that if the MzLauncher is used it uses the execution engine flags from the .she-file /// </summary> /// <param name="MsheFileName"></param> /// <param name="UseMZLauncher"></param> public static void PreprocessAndRun(string MsheFileName, bool UseMZLauncher) { Process Runner = new Process(); string path; DHIRegistry key = new DHIRegistry(DHIProductAreas.COMMON_COMPONNETS, false); key.GetHomeDirectory(out path); if (UseMZLauncher) { Runner.StartInfo.FileName = Path.Combine(path,"Mzlaunch.exe"); Runner.StartInfo.Arguments = Path.GetFullPath(MsheFileName) + " -exit"; } else { Runner.StartInfo.FileName = Path.Combine(path,"Mshe_preprocessor.exe"); Runner.StartInfo.Arguments = MsheFileName; Runner.Start(); Runner.WaitForExit(); Runner.StartInfo.FileName = Path.Combine(path,"Mshe_watermovement.exe"); } Runner.Start(); Runner.WaitForExit(); Runner.Close(); }
public Boolean Start() { //FileInfo commandFile = new FileInfo(_commandFullPath); //if(commandFile.Exists == false) throw new FileNotFoundException(); Boolean result = false; Process p = new Process(); p.StartInfo.FileName = _command; if(_arugment.IsNullOrEmpty() == false) p.StartInfo.Arguments = _arugment; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; // These two optional flags ensure that no DOS window appears p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.Start(); p.WaitForExit(); ErrorMessage = p.StandardError.ReadToEnd(); OutputMessage = p.StandardOutput.ReadToEnd(); if(p.ExitCode == 0) result = true; p.Close(); p.Dispose(); return result; }
public static bool CmdPing(string strIp) { bool pingRst = false; Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine("ping -n 1 " + strIp); p.StandardInput.WriteLine("exit"); string strRst = p.StandardOutput.ReadToEnd(); if (strRst.IndexOf("(0% loss)") != -1 || strRst.IndexOf("(0% 丢失)") != -1) pingRst = true; else pingRst = false; p.Close(); return pingRst; }
/// <summary> /// 编译指定目录下的文件 /// </summary> /// <param name="root">源代码目录</param> /// <param name="outputDllName">编译输出的dll名称</param> /// <param name="references">编译时需要的引用程序集</param> public static void Compile(String root, String outputDllName, params String[] references) { var args = BuildCompileArgs(root, outputDllName, references); var cmd = Path.Combine(MonoLocation, "bin/mcs").ToConsistentPath(); UnityEngine.Debug.Log(String.Format("{0} {1}", cmd, args)); #if UNITY_EDITOR_OSX var proc = new Process { StartInfo = { FileName = cmd, Arguments = args, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true } }; #else var proc = new Process { StartInfo = { FileName = cmd, Arguments = args, UseShellExecute = true } }; #endif proc.Start(); proc.WaitForExit(); proc.Close(); }
/// <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); } }
static void Main(string[] args) { ProcessStartInfo gitInfo = new ProcessStartInfo(); gitInfo.CreateNoWindow = true; gitInfo.RedirectStandardError = true; gitInfo.RedirectStandardOutput = true; gitInfo.FileName = @"C:\Program Files\Git\bin\git.exe"; Process gitProcess = new Process(); if (args[0] == "pull") { gitInfo.Arguments = "pull"; } else if (args[0] == "push") { gitInfo.Arguments = "push --all origin"; } gitInfo.WorkingDirectory = args[1]; gitInfo.UseShellExecute = false; gitProcess.StartInfo = gitInfo; gitProcess.Start(); string stderr_str = gitProcess.StandardError.ReadToEnd(); //string stdout_str = gitProcess.StandardOutput.ReadToEnd(); // pick up STDOUT gitProcess.WaitForExit(); gitProcess.Close(); }
protected override void OnAfterInstall(IDictionary savedState) { if (Environment.Is64BitOperatingSystem) { try { Process reg = new Process { StartInfo = { FileName = "regsvr32.exe", Arguments = @"C:\Krypton\Output\AutoItX3_x64.dll", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true } }; //This file registers .dll files as command components in the registry. reg.Start(); reg.WaitForExit(); reg.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } base.OnAfterInstall(savedState); }
private static void FormatFile(string sFile) { try { if ((File.GetAttributes(sFile) & FileAttributes.ReadOnly) != FileAttributes.ReadOnly) { // Make sure it's an xml file XmlDocument doc = new XmlDocument(); doc.Load(sFile); // It is, so now process it. using (Process myProcess = new Process()) { string workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6); Console.WriteLine("Formatting {0}", sFile); myProcess.StartInfo.FileName = Path.Combine(workingDir, @"Xmlformatter\XMLFormat"); myProcess.StartInfo.Arguments = sFile + " " + workingDir; myProcess.StartInfo.CreateNoWindow = true; myProcess.Start(); while (!myProcess.HasExited) {} // Wait until it gets done. myProcess.Close(); } } } catch (XmlException xmlerr) { Console.WriteLine("Error message: {0}.", xmlerr.Message); Console.WriteLine("Error: {0} is not an xml file!", sFile); } catch (Exception err) { Console.WriteLine("Error: " + err.Message); } }
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(); } }
/// <summary> /// Runs the command. (*.cmd, *.bat, *.exe, etc.) /// </summary> /// <param name="commandFilePath">The command file path. (*.cmd, *.bat, *.exe, etc.)</param> /// <param name="outputDelegate">The output delegate.</param> public static void RunCommand(string commandFilePath, Action<string> outputDelegate) { if (!string.IsNullOrWhiteSpace(commandFilePath) && File.Exists(commandFilePath)) { Process batProcess = new Process(); // Redirect the output stream of the child process. batProcess.StartInfo.UseShellExecute = false; batProcess.StartInfo.RedirectStandardOutput = true; batProcess.StartInfo.RedirectStandardError = true; batProcess.StartInfo.FileName = commandFilePath; if (outputDelegate != null) { batProcess.OutputDataReceived += (sender, args) => outputDelegate(args.Data); batProcess.ErrorDataReceived += (sender, args) => outputDelegate(args.Data); } batProcess.Start(); batProcess.BeginOutputReadLine(); batProcess.WaitForExit(); batProcess.Close(); } }
public override bool Execute() { try { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; //设置为false将会看到程序窗口 p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //启动进程时窗口状态 p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = Path.GetFullPath(this.FileName); //如果a.bat在System32文件夹中,此处只需填写文件名即可 p.StartInfo.WorkingDirectory = Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(this.FileName)); //工作目录 p.Start(); Log.LogMessage("FileName:{0}", p.StartInfo.FileName); Log.LogMessage("WorkingDirectory:{0}", p.StartInfo.WorkingDirectory); var result = p.StandardOutput.ReadToEnd(); p.WaitForExit(); p.Close(); Log.LogMessage(result); Log.LogMessage("Bat executed."); return result.Contains("Liquibase Update Successful"); } catch (Exception ex) { Log.LogError(ex.Message); } return false; }
public static string startcmd(string command, string argument) { string output = ""; try { Process cmd = new Process(); cmd.StartInfo.FileName = command; cmd.StartInfo.Arguments = argument; cmd.StartInfo.UseShellExecute = false; cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; cmd.Start(); output = cmd.StandardOutput.ReadToEnd(); Console.WriteLine(output); cmd.WaitForExit(); cmd.Close(); } catch (Exception e) { Console.WriteLine(e); } return output; }
public bool runFileExe(string cmd, string para, bool hiddenCmd) { try { Process myProgram = new Process(); //Process.Start(cmd, para); myProgram.StartInfo.FileName = cmd; myProgram.StartInfo.Arguments = para; if (hiddenCmd) { myProgram.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; myProgram.StartInfo.UseShellExecute = false; myProgram.StartInfo.CreateNoWindow = true; myProgram.EnableRaisingEvents = true; } myProgram.Start(); myProgram.WaitForExit(); myProgram.Close(); return true; } catch (Exception ex) { return false; } }
private bool WinrarProcess(string arguments) { try { Process winrar = new Process(); winrar.StartInfo.FileName = "winrar.exe"; winrar.StartInfo.CreateNoWindow = true; winrar.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; winrar.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; winrar.StartInfo.Arguments = arguments; winrar.Start(); winrar.WaitForExit(); if (winrar.HasExited) { int iExitCode = winrar.ExitCode; if (iExitCode == 0) { //正常完成 return true; } else { //有错 return false; } } winrar.Close(); return false; } catch { return false; } }
/// /// 执行多条cmd.exe命令 /// ///命令文本数组 /// 命令输出文本 public static string ExeCommand(string[] commandTexts) { Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; string strOutput = null; try { p.Start(); foreach (string item in commandTexts) { p.StandardInput.WriteLine(item); } p.StandardInput.WriteLine("exit"); strOutput = p.StandardOutput.ReadToEnd(); //strOutput = Encoding.UTF8.GetString(Encoding.Default.GetBytes(strOutput)); p.WaitForExit(); p.Close(); } catch (Exception e) { strOutput = e.Message; } return strOutput; }
public string ProcessPhpPage(string phpCompilerPath, string pageFileName) { Process proc = new Process(); proc.StartInfo.FileName = phpCompilerPath; proc.StartInfo.Arguments = "-d \"display_errors=1\" -d \"error_reporting=E_PARSE\" \"" + pageFileName + "\""; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.Start(); string res = proc.StandardOutput.ReadToEnd(); if (string.IsNullOrEmpty(res)) { res = proc.StandardError.ReadToEnd(); res = "<h2 style=\"color:red;\">Error!</h2><hr/> <h4>Error Details :</h4> <pre>" + res + "</pre>"; proc.StandardError.Close(); } if (res.StartsWith("\nParse error: syntax error")) res = "<h2 style=\"color:red;\">Error!</h2><hr/> <h4>Error Details :</h4> <pre>" + res+"</pre>"; proc.StandardOutput.Close(); proc.Close(); return res; }
/// <summary> /// Validates a variant string, returns true if variant string is a correct HVGS nomnclature /// </summary> /// <param name="variant"></param> /// <returns></returns> public bool VariantValidate(string variant) { try { Process process = new Process(); if (ApplicationDeployment.IsNetworkDeployed) process.StartInfo.FileName = ApplicationDeployment.CurrentDeployment.DataDirectory + "\\Executables\\Validator.exe"; else process.StartInfo.FileName = Application.StartupPath + "\\Executables\\Validator.exe"; process.StartInfo.Arguments = "-v " + "\"" + variant + "\""; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); process.Close(); return bool.Parse(output); } catch (Exception ex) { // something went wrong, we log it Log log = new Log(true); log.write("Error parsing variant: " + variant); log.write(ex.ToString()); return false; } }
public static void CheckForUpdate() { #if !DEBUG _executableFileInfo = new FileInfo(ExecutableName); _executableDirectoryName = _executableFileInfo.DirectoryName; _ourDirectory = _executableDirectoryName; try { var proc = new Process { StartInfo = new ProcessStartInfo(_ourDirectory + "\\wyUpdate.exe", "-quickcheck -justcheck -noerr") }; proc.Start(); proc.WaitForExit(); int exitCode = proc.ExitCode; proc.Close(); if (exitCode == 2) { MessageBox.Show(@"New update ready. Closing to update"); Process.Start(_ourDirectory + "\\wyUpdate.exe"); Environment.Exit(0); } } catch (Exception e) { Logging.Write("Could not start the updating program, cannot auto update: " + e); } #endif }
/// <summary> /// 执行命令行 /// </summary> /// <param name="cmd"></param> /// <returns></returns> public static string Cmd(string command) { string output = ""; //输出字符串 if (command != null && !command.Equals("")) { Process process = new Process();//创建进程对象 ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe";//设定需要执行的命令 startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出 startInfo.UseShellExecute = false;//不使用系统外壳程序启动 startInfo.RedirectStandardInput = false;//不重定向输入 startInfo.RedirectStandardOutput = true; //重定向输出 startInfo.CreateNoWindow = true;//不创建窗口 process.StartInfo = startInfo; try { if (process.Start())//开始进程 { process.WaitForExit();//这里无限等待进程结束 output = process.StandardOutput.ReadToEnd();//读取进程的输出 } } catch { } finally { if (process != null) process.Close(); } } return output; }
/// <summary> /// Try to start SQL Server service if it is not running. /// </summary> /// <remarks> /// This is used to handle the issue that SQL Server service stops for unknown reason. /// </remarks> /// <returns> /// 0: Already running, nothing to do /// 1: Success to start /// 2: Failed to start /// </returns> public void StartSqlServer() { logger.Debug("Checking sql server service..."); int result = 0; Process[] sqlservers = Process.GetProcessesByName("sqlservr"); if (sqlservers.Length == 0) { try { var sqlinstance = GetSqlServerInstance(); Process process = new Process(); process.StartInfo.FileName = "net"; process.StartInfo.Arguments = "start " + sqlinstance; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); process.Close(); sqlservers = Process.GetProcessesByName("sqlservr"); if (sqlservers.Length > 0) { result = 1; logger.Info("Sql server started"); } else { result = 2; logger.Info("Sql server failed to start"); } } catch (Exception ex) { logger.Error("Failed to start sql server.\r\n", ex); result = 2; } } logger.Debug("Starting service result: " + result.ToString()); }
public static bool HtmltoPdf(string Url, string outputFilename) { string filename = outputFilename; Process p = new System.Diagnostics.Process(); p.StartInfo.Arguments = Url + " " + filename; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/bin/") + "wkhtmltopdf.exe"; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardInput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(60000); // read the exit code, close process int returnCode = p.ExitCode; p.Close(); // if 0 or 2, it works return (returnCode == 0 || returnCode == 2); }
//------------------------------------------------------------------------- public static string RunCommand( string command ) { string output = ""; using( Process p = new Process() ) { p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "p4.exe"; p.StartInfo.Arguments = command; p.StartInfo.ErrorDialog = true; if( Program.LoggedOnUser != null ) { p.StartInfo.EnvironmentVariables.Add( "P4USER", Program.LoggedOnUser.Username ); } p.Start(); output = p.StandardOutput.ReadToEnd(); p.WaitForExit( 1000 ); p.Close(); } return output; }
/// <summary> /// 使用Process编译,指定目录下所有匹配的文件 /// </summary> /// <param name="parameter">The parameter.</param> private static string BuildMatchingFile(string parameter) { string result; Process process = null; try { process = new Process(); process.StartInfo.FileName = "CMD"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.Arguments = parameter; process.Start(); //process.WaitForExit(); result = process.StandardOutput.ReadToEnd(); process.Close(); } finally { if (process != null) process.Dispose(); } return result; }
public static int runCommandAndGetOutput(string exeFile, string args, ref string output) { string str = null; Process process = new Process(); int exitCode = -1; ProcessStartInfo info = new ProcessStartInfo { FileName = exeFile, Arguments = args, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true }; process.StartInfo = info; try { process.Start(); process.WaitForExit(); str = process.StandardError.ReadToEnd() + process.StandardOutput.ReadToEnd(); exitCode = process.ExitCode; output = str; process.Close(); return exitCode; } catch (Exception exception) { output = exception.Message; return -1; } }
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 bool SyncStart(string CmdName, string CmdArgv) { m_Proc = new Process(); m_Proc.StartInfo.FileName = CmdName; m_Proc.StartInfo.Arguments = CmdArgv; m_Proc.StartInfo.CreateNoWindow = true; m_Proc.StartInfo.UseShellExecute = false; m_Proc.StartInfo.RedirectStandardInput = true;//标准输入重定向 m_Proc.StartInfo.RedirectStandardOutput = true;//标准输出重定向 m_Proc.StartInfo.RedirectStandardError = true; m_Proc.Start(); StreamReader reader = m_Proc.StandardOutput; m_Proc.WaitForExit(); m_RetOutputMsg = new StringBuilder(); m_RetOutputMsg.Append(reader.ReadToEnd()); reader = m_Proc.StandardError; m_RetErrorMsg = reader.ReadToEnd(); int RetCode = m_Proc.ExitCode; m_Proc.Close(); reader.Close(); if (RetCode == 0) { return true; } else { return false; } }
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 IDisposable CreateProcessExitSubscription(System.Diagnostics.Process process, IObservable <EventPattern <object> > processExited, IObserver <string> observer) { return(processExited.Subscribe(args => { try { this.ExitCode = process?.ExitCode; if (process?.ExitCode > 0) { observer.OnError(new Exception( $"Process '{process.StartInfo.FileName}' terminated with error code {process.ExitCode}")); } else { observer.OnCompleted(); } } finally { this.Started = false; process?.Close(); } })); }
public void Dispose() { if (!_isClosed) { _isClosed = true; _cancellationSource.Cancel(); if (_localProcess != null) { _localProcess.Exited -= OnProcessExited; } _localProcess?.Close(); _stdoutWriter?.Close(); _localProcess = null; _stdoutWriter = null; } }
public static void HandleSprotoBundle(string streamPath) { string tool_path = Application.dataPath.Replace("/Assets", "") + "/Tools/sprotodumper/"; string names = Util.GetFileNamesInFolder(AppConfig.LuaAssetsDir + "/Common/Proto", " "); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动 p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 p.StartInfo.CreateNoWindow = true;//不显示程序窗口 p.Start();//启动程序 //向cmd窗口发送输入信息 p.StandardInput.WriteLine("cd \\"); p.StandardInput.WriteLine("cd I:"); p.StandardInput.WriteLine(@"cd "+ tool_path); p.StandardInput.WriteLine("lua sprotodumper.lua " + names+ "&exit"); p.StandardInput.AutoFlush = true; //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死 //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令 //获取cmd窗口的输出信息 string output = p.StandardOutput.ReadToEnd(); p.WaitForExit();//等待程序执行完退出进程 p.Close(); if (output.Contains("succeed!")) { UnityEngine.Debug.Log("generate sproto spb succeed!"); File.Copy(tool_path + "/sproto_c2s.spb", streamPath + "/sproto_c2s.spb"); File.Copy(tool_path + "/sproto_s2c.spb", streamPath + "/sproto_s2c.spb"); } else { UnityEngine.Debug.Log(output); UnityEngine.Debug.Log("generate sproto spb failed! please check up line for detail"); } }
public WebExtractSession(string filePath) { DataDirectory = filePath + "_data"; if (Directory.Exists(DataDirectory)) { throw new Exception("Bundle data directory already exists"); } var baseDir = Path.GetDirectoryName(EditorApplication.applicationPath); var webExtractFiles = Directory.GetFiles(baseDir, "WebExtract*", SearchOption.AllDirectories); string webExtractPath = webExtractFiles[0]; Assert.IsTrue(File.Exists(filePath), "Param filePath does not point to an existing file."); var process = new System.Diagnostics.Process { StartInfo = { FileName = webExtractPath, Arguments = string.Format(@"""{0}""", filePath), UseShellExecute = false, RedirectStandardOutput = true } }; process.Start(); var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); var exitCode = process.ExitCode; process.Close(); Assert.AreEqual(0, exitCode); Files = Directory.GetFiles(DataDirectory); }
public static void ProcessCommand(string command, string argument, string workPath = "") { System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(command); info.Arguments = argument; info.CreateNoWindow = false; info.ErrorDialog = true; info.UseShellExecute = true; if (!string.IsNullOrEmpty(workPath)) { info.WorkingDirectory = workPath; } if (info.UseShellExecute) { info.RedirectStandardOutput = false; info.RedirectStandardError = false; info.RedirectStandardInput = false; } else { info.RedirectStandardOutput = true; info.RedirectStandardError = true; info.RedirectStandardInput = true; info.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8; info.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8; } System.Diagnostics.Process process = System.Diagnostics.Process.Start(info); if (!info.UseShellExecute) { Debug.Log(process.StandardOutput); Debug.Log(process.StandardError); } //process.WaitForExit(); process.Close(); }
/// <summary> /// PDF格式转为SWF /// </summary> /// <param name="pdfPath">PDF文件地址</param> /// <param name="swfPath">生成后的SWF文件地址</param> /// <param name="beginpage">转换开始页</param> /// <param name="endpage">转换结束页</param> private static bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality) { //swftool,首先先安装,然后将安装目录下的东西拷贝到tools目录下 string exe = HttpContext.Current.Server.MapPath("~/bin/tools/pdf2swf.exe"); //pdfPath = HttpContext.Current.Server.MapPath(pdfPath); swfPath = HttpContext.Current.Server.MapPath(swfPath); if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath) || System.IO.File.Exists(swfPath)) { return(false); } StringBuilder sb = new StringBuilder(); sb.Append(" \"" + pdfPath + "\""); sb.Append(" -o \"" + swfPath + "\""); sb.Append(" -s languagedir=xpdf-chinese-simplified"); if (endpage > GetPageCount(pdfPath)) { endpage = GetPageCount(pdfPath); } sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\""); sb.Append(" -j " + photoQuality); string Command = sb.ToString(); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = exe; p.StartInfo.Arguments = Command; p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/bin/"); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false; p.Start(); p.BeginErrorReadLine(); p.WaitForExit(); p.Close(); p.Dispose(); return(true); }
// Runs the "filename" R script and returns the output void RunRScript(string filename) { var watch = System.Diagnostics.Stopwatch.StartNew(); start.Arguments = filename; /* * using (System.Diagnostics.Process process = System.Diagnostics.Process.Start(start)) * { * using (StreamReader reader = process.StandardOutput) * { * //output = reader.ReadLine(); * } * * //process.WaitForExit(); * } */ System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = start; process.Start(); // StreamReader reader = process.StandardOutput; // var output = reader.ReadToEnd(); // string err = process.StandardError.ReadToEnd(); // Debug.Log(err); // process.StandardOutput.Close(); // process.WaitForExit(); process.Close(); watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; Debug.Log(elapsedMs); }
public static string YaSuo(string PathSave, string FilePath, string WinRAR) { string rarurlPath = string.Empty; Boolean bo = false; System.Diagnostics.Process pro = new System.Diagnostics.Process(); pro.StartInfo.FileName = WinRAR;//WinRAR所在路径 //pro.StartInfo.Arguments = "a " + yasuoPathSave + " " + yasuoPath + " -r ";//dir是你的目录名 pro.StartInfo.Arguments = string.Format("a {0} {1} -r", PathSave, FilePath); pro.Start(); TimeSpan times = pro.TotalProcessorTime; bo = pro.WaitForExit(60000);//设定一分钟 if (!bo) { pro.Kill(); } pro.Close(); pro.Dispose(); rarurlPath = PathSave; return(rarurlPath); }
protected Boolean pdf2jsonEnabled(String lpath_to_pdf2swf) { try { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = lpath_to_pdf2swf; proc.StartInfo.Arguments = " --help 2>&1"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.Start(); string output = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); proc.Close(); return(output.ToLower().IndexOf("devaldi") >= 0); } catch { return(false); } }
static bool Exec(string filename, string args) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = filename; process.StartInfo.Arguments = args; int exit_code = -1; try { process.Start(); if (process.StartInfo.RedirectStandardOutput && process.StartInfo.RedirectStandardError) { process.BeginOutputReadLine(); Debug.LogError(process.StandardError.ReadToEnd()); } else if (process.StartInfo.RedirectStandardOutput) { string data = process.StandardOutput.ReadToEnd(); Debug.Log(data); } else if (process.StartInfo.RedirectStandardError) { string data = process.StandardError.ReadToEnd(); Debug.LogError(data); } } catch (Exception e) { Debug.LogException(e); return(false); } process.WaitForExit(); exit_code = process.ExitCode; process.Close(); return(exit_code == 0); }
/// Executes a command-line. Blocks the calling thread until the new process has completed. Returns the logged stdout in one big string. public static string ExecuteCommandLine(string command, string arguments) { var process = new System.Diagnostics.Process(); process.StartInfo.FileName = command; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.Arguments = arguments; process.Start(); // Synchronously read the standard output of the spawned process. var reader = process.StandardOutput; var output = reader.ReadToEnd(); // Waiting for the process to exit directly in the UI thread. Similar cases are working that way too. // TODO: Is it better to provide a timeout avoid any issues of forever blocking the UI thread? If so, what is // a relevant timeout value for SoundBank generation? process.WaitForExit(); process.Close(); return(output); }
public static string ProcessCommand(string command, string argument) { System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo(command); start.Arguments = argument; start.CreateNoWindow = false; start.ErrorDialog = true; start.UseShellExecute = false; if (start.UseShellExecute) { start.RedirectStandardOutput = false; start.RedirectStandardError = false; start.RedirectStandardInput = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(start); p.WaitForExit(); p.Close(); return(""); } else { start.RedirectStandardOutput = true; start.RedirectStandardError = true; // start.RedirectStandardInput = true; start.StandardOutputEncoding = System.Text.Encoding.UTF8; start.StandardErrorEncoding = System.Text.Encoding.UTF8; System.Diagnostics.Process p = System.Diagnostics.Process.Start(start); p.WaitForExit(); string error = p.StandardError.ReadToEnd(); string output = p.StandardOutput.ReadToEnd(); p.Close(); Debug.Log("ProcessCommand OutPut:" + output); return(error); } }
/// <summary> /// PDF格式转为SWF /// </summary> /// <param name="pdfPath">PDF文件地址</param> /// <param name="swfPath">生成后的SWF文件地址</param> /// <param name="beginpage">转换开始页</param> /// <param name="endpage">转换结束页</param> public static bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality) { string exe = AppDomain.CurrentDomain.BaseDirectory + "\\SWFTool\\pdf2swf.exe"; if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath) || System.IO.File.Exists(swfPath)) { return(false); } StringBuilder sb = new StringBuilder(); sb.Append(" \"" + pdfPath + "\""); sb.Append(" -o \"" + swfPath + "\""); sb.Append(" -f -T 9 -s poly2bitmap "); if (endpage > GetPageCount(pdfPath)) { endpage = GetPageCount(pdfPath); } sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\""); sb.Append(" -G "); sb.Append(" -j " + photoQuality); string Command = sb.ToString(); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = exe; p.StartInfo.Arguments = Command; //p.StartInfo.WorkingDirectory = //HttpContext.Current.Server.MapPath("~/Bin/"); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false; p.Start(); p.BeginErrorReadLine(); p.WaitForExit(); p.Close(); p.Dispose(); return(true); }
private void NugetPush(string configuration) { System.Diagnostics.Process p = null; try { var projects = (UIHierarchyItem[])_dte?.ToolWindows.SolutionExplorer.SelectedItems; var project = projects[0].Object as Project; var projectDir = Path.GetDirectoryName(project.FullName); var projectPath = Path.Combine(projectDir ?? throw new InvalidOperationException()); p = new System.Diagnostics.Process(); p.StartInfo.FileName = @"C:\WINDOWS\system32\cmd.exe "; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine(projectDir.Substring(0, 2)); p.StandardInput.WriteLine($"cd {projectDir.Substring(2)}"); p.StandardInput.WriteLine($"del {projectPath}\\*.nupkg /s/q"); //先转到系统盘下 p.StandardInput.WriteLine($"nuget pack {project.Name}.csproj -Prop Configuration={configuration}"); p.StandardInput.WriteLine($"nuget push *.nupkg -Source http://10.3.1.240:8080/nuget -ApiKey Benchint"); p.StandardInput.WriteLine("exit"); p.WaitForExit(); ShowMessageBox("success"); } catch (Exception ex) { ShowMessageBox(ex.Message); } finally { p?.Close(); p?.Dispose(); } }
private static void ExecuteCMDCommand(string command) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/C " + command; process.StartInfo = startInfo; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); string error = process.StandardError.ReadToEnd(); string output = process.StandardOutput.ReadToEnd(); if (string.IsNullOrEmpty(output)) { Debug.Log("<color=blue>No output</color>"); } else { Debug.Log("<color=blue>Output: " + output + "</color>"); } if (string.IsNullOrEmpty(error)) { Debug.Log("<color=green>No errors</color>"); } else { Debug.LogError("Error: " + error); } process.Close(); }
public void DoUpdateCharacterList(SheetsReference[] sheetIds, string destination) { string prams = GetParams(); Debug.Log(prams); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "python"; p.StartInfo.Arguments = $"character_list_generator.py {prams}"; // Pipe the output to itself - we will catch this later p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; // Where the script lives p.StartInfo.WorkingDirectory = GetPythonFolder(); p.StartInfo.UseShellExecute = false; Debug.Log($"python {p.StartInfo.Arguments}"); p.Start(); pythonOutput = p.StandardOutput.ReadToEnd(); Debug.Log(pythonOutput); p.WaitForExit(); p.Close(); }
public static void Close() { System.Diagnostics.Process p = cmdStack.Pop(); p.Close(); }
private void CreateSubversionProj() { // return; /* * from jeremy: * string _systemRoot = Environment.GetEnvironmentVariable("SYSTEMROOT"); * * ProcessStartInfo _processStartInfo = new ProcessStartInfo(); * _processStartInfo.WorkingDirectory = @"%ProgramFiles%"; * _processStartInfo.FileName = @"Notepad.exe"; * _processStartInfo.Arguments = "test.txt"; * _processStartInfo.CreateNoWindow = true; * Process myProcess = Process.Start(_processStartInfo); */ // Get the full file path string strFilePath = Server.MapPath("fine.bat"); // Create the ProcessInfo object System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe"); psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardInput = true; psi.RedirectStandardError = true; // Start the process System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); // Open the batch file for reading //System.IO.StreamReader strm = // System.IO.File.OpenText(strFilePath); System.IO.StreamReader strm = proc.StandardError; // Attach the output for reading System.IO.StreamReader sOut = proc.StandardOutput; // Attach the in for writing // System.IO.StreamWriter sIn = proc.StandardInput; // Write each line of the batch file to standard input /*while(strm.Peek() != -1) * { * sIn.WriteLine(strm.ReadLine()); * }*/ // sIn.WriteLine(exec); string errors = strm.ReadToEnd().Trim(); strm.Close(); Web.WriteLine("Errors: " + errors); // Exit CMD.EXE // string stEchoFmt = "# {0} run successfully. Exiting"; // sIn.WriteLine(String.Format(stEchoFmt, strFilePath)); // sIn.WriteLine("EXIT"); // Close the process proc.Close(); // Read the sOut to a string. string results = sOut.ReadToEnd().Trim(); // Close the io Streams; // sIn.Close(); sOut.Close(); // Write out the results. string fmtStdOut = "<font face=courier size=0>{0}</font>"; this.Response.Write("<br>"); this.Response.Write("<br>"); this.Response.Write("<br>"); this.Response.Write(String.Format(fmtStdOut, results.Replace(System.Environment.NewLine, "<br>"))); }
static void GenerateAdapter() { MsdkUtil.ReplaceDir(env.PATH_ADAPTER_ANDROID + "/java", env.PATH_TEMP + "/java"); MsdkUtil.ReplaceTextWithRegex(env.PATH_TEMP + "/java/src/com/tencent/msdk/adapter/MsdkActivity.java", srcFileRules); MsdkUtil.ReplaceText(env.PATH_TEMP + "/java/src/com/example/wegame/MGameActivity.java", "com.example.wegame", game.BundleId); MsdkUtil.ReplaceText(env.PATH_TEMP + "/java/src/com/example/wegame/wxapi/WXEntryActivity.java", "com.example.wegame", game.BundleId); File.Move(env.PATH_TEMP + "/java/src/com/example/wegame/MGameActivity.java", env.PATH_TEMP + "/java/src/MGameActivity.java"); File.Move(env.PATH_TEMP + "/java/src/com/example/wegame/wxapi/WXEntryActivity.java", env.PATH_TEMP + "/java/src/WXEntryActivity.java"); Directory.Delete(env.PATH_TEMP + "/java/src/com/example", true); string packagePath = game.BundleId.Replace(".", "/"); packagePath = packagePath.Trim(); Directory.CreateDirectory(env.PATH_TEMP + "/java/src/" + packagePath); File.Move(env.PATH_TEMP + "/java/src/MGameActivity.java", env.PATH_TEMP + "/java/src/" + packagePath + "/MGameActivity.java"); Directory.CreateDirectory(env.PATH_TEMP + "/java/src/" + packagePath + "/wxapi"); File.Move(env.PATH_TEMP + "/java/src/WXEntryActivity.java", env.PATH_TEMP + "/java/src/" + packagePath + "/wxapi/WXEntryActivity.java"); string msdkUnityJar = ADAPTER_JARFILE_PREFIX + WGPlatform.Version + ".jar"; string androidSdkJar = ""; string androidSdkRoot = EditorPrefs.GetString("AndroidSdkRoot"); if (!Directory.Exists(androidSdkRoot)) { env.Error("Android Sdk Location Error! Check on \"Preferences->External Tools \""); return; } string[] platforms = Directory.GetDirectories(androidSdkRoot + "/platforms"); string[] platformsTemp = platforms.Where(str => Regex.IsMatch(str, @"android-\d\d$")).ToArray(); if (platformsTemp.Length != 0) { platforms = platformsTemp; } else { platforms = platforms.Where(str => Regex.IsMatch(str, @"android-\d$")).ToArray(); } System.Array.Sort(platforms, System.StringComparer.Ordinal); for (int i = 1; i <= platforms.Length; i++) { androidSdkJar = platforms[platforms.Length - i] + "/android.jar"; if (File.Exists(androidSdkJar)) { break; } } if (!File.Exists(androidSdkJar)) { env.Error("Find android.jar error in " + androidSdkRoot + "/platforms"); } string[] msdkJarFile = Directory.GetFiles(DIR_MSDKLIBRARY + "/libs", "MSDK_Android_*.jar"); /* 此目录中应只有一个 MSDK jar 包 */ if (msdkJarFile.Length != 1) { env.Error("Get MSDK jar file error! Check jar file in " + DIR_MSDKLIBRARY + "/libs"); return; } string msdkLibraryJar = msdkJarFile [0]; #if UNITY_EDITOR_WIN string shellFile = env.PATH_TEMP + "/java/MsdkAdapter.bat"; string dirRoot = Path.GetPathRoot(env.PATH_TEMP); dirRoot = dirRoot.Replace("\\", ""); MsdkUtil.ReplaceText(shellFile, "DirRoot", dirRoot); #elif UNITY_EDITOR_OSX string shellFile = env.PATH_TEMP + "/java/MsdkAdapter.sh"; #else string shellFile = ""; #endif MsdkUtil.ReplaceText(shellFile, "MSDKUnityLibrary", env.PATH_TEMP + "/java"); MsdkUtil.ReplaceText(shellFile, "MSDKUnityJar", msdkUnityJar); MsdkUtil.ReplaceText(shellFile, "MSDKLibraryJar", msdkLibraryJar); MsdkUtil.ReplaceText(shellFile, "AndroidSdkJar", androidSdkJar); MsdkUtil.ReplaceText(shellFile, "UnityJar", env.PATH_LIBRARYS_ANDROID + "/UnityClasses.jar"); MsdkUtil.ReplaceText(shellFile, "GamePackage", packagePath); Debug.Log(File.ReadAllText(shellFile)); shellFile = "\"" + shellFile + "\""; Encoding utf8WithoutBom = new UTF8Encoding(false); System.Diagnostics.Process shell = new System.Diagnostics.Process(); #if UNITY_EDITOR_WIN shell.StartInfo.FileName = "cmd.exe"; #elif UNITY_EDITOR_OSX shell.StartInfo.FileName = "sh"; #endif shell.StartInfo.UseShellExecute = false; shell.StartInfo.RedirectStandardInput = true; shell.StartInfo.RedirectStandardOutput = true; shell.StartInfo.RedirectStandardError = true; #if UNITY_EDITOR_WIN Encoding gb = Encoding.GetEncoding("gb2312"); shell.StartInfo.StandardOutputEncoding = gb; shell.StartInfo.StandardErrorEncoding = gb; #endif shell.StartInfo.CreateNoWindow = true; shell.Start(); Stream input = shell.StandardInput.BaseStream; StreamWriter myIn = new StreamWriter(input, utf8WithoutBom); #if UNITY_EDITOR_OSX myIn.WriteLine("chmod a+x " + shellFile); #endif myIn.WriteLine(shellFile); myIn.WriteLine("exit"); myIn.AutoFlush = true; myIn.Close(); if (!shell.WaitForExit(5000)) { env.Error("Execute shell command out time! Check Console for Detail"); } if (shell.StandardError.Peek() != -1) { env.Error("Execute shell command return error! Check Console for Detail"); env.Error(shell.StandardError.ReadToEnd()); } shell.Close(); string outputJar = env.PATH_TEMP + "/java/classes/" + msdkUnityJar; if (!File.Exists(outputJar)) { env.Error("Generate " + msdkUnityJar + " error! Check Console for Detail"); } else { string[] adapterJars = Directory.GetFiles(env.PATH_PUGLIN_ANDROID + "/libs/"); foreach (string file in adapterJars) { if (file.IndexOf(ADAPTER_JARFILE_PREFIX) >= 0) { File.Delete(file); } } string targetJar = env.PATH_PUGLIN_ANDROID + "/libs/" + msdkUnityJar; File.Move(outputJar, targetJar); } }
/// <summary> /// 打开软件比较两个文件 /// </summary> /// <param name="oldFilePath">旧文件</param> /// <param name="newFilePath">新文件</param> /// <param name="needCopy">为true时,比较文件副本</param> /// <returns>是否成功打开</returns> public bool Compare(string fileFullName1, string fileFullName2, string fileTitle1, string fileTitle2, bool needCopy = false) { if (!Initialized()) { return(false); } if (needCopy) { try { string copyFileFullName = Path.GetTempPath() + "CsvEditorCompare1"; File.Copy(fileFullName1, copyFileFullName); fileFullName1 = copyFileFullName; copyFileFullName = Path.GetTempPath() + "CsvEditorCompare2"; File.Copy(fileFullName2, copyFileFullName); fileFullName2 = copyFileFullName; } catch (Exception ex) { DebugUtility.ShowExceptionMessageBox("拷贝副本: " + fileFullName1 + " - " + fileFullName2 + " 失败", ex); return(false); } } // 执行CMD命令 try { using (System.Diagnostics.Process cmdProcess = new System.Diagnostics.Process()) { cmdProcess.StartInfo.FileName = "cmd.exe"; // 是否使用操作系统shell启动 cmdProcess.StartInfo.UseShellExecute = false; // 接受来自调用程序的输入信息 cmdProcess.StartInfo.RedirectStandardInput = true; // 由调用程序获取输出信息 cmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向标准错误输出 cmdProcess.StartInfo.RedirectStandardError = true; // 不显示程序窗口 cmdProcess.StartInfo.CreateNoWindow = true; cmdProcess.Start(); // 向cmd窗口发送输入信息 // 向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死 // 同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令 cmdProcess.StandardInput.WriteLine(GetCmdProcessLine(fileFullName1, fileFullName2, fileTitle1, fileTitle2)); // UNDONE 暂时不需要接受数据 //Console.WriteLine(cmdProcess.StandardOutput.ReadToEnd()); // 等待程序执行完退出进程 cmdProcess.WaitForExit(); cmdProcess.Close(); } } catch (Exception ex) { DebugUtility.ShowExceptionMessageBox("比较文件: " + fileFullName1 + " - " + fileFullName2 + " 失败", ex); return(false); } return(true); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Event handler. Called by btnConfigurar for click events. </summary> /// /// <remarks> Evento que lanza el proceso de configuración de XMLTV. Se lanza el proceso /// que escribe en la entrada estándar las respuestas necesarias para ejecutar el proceso.</remarks> /// /// <param name="sender"> Source of the event. </param> /// <param name="e"> Event information. </param> //////////////////////////////////////////////////////////////////////////////////////////////////// private void btnConfigurar_Click(object sender, EventArgs e) { btnConfigurar.Enabled = false; System.Diagnostics.Process p = new System.Diagnostics.Process(); try { MensajeSistema(etInfoXML, "Iniciando proceso de configuración...", kMensajeSistema.mADVERTENCIA); gbInfoXML.Visible = true; // System.Diagnostics.Process.Start("xmltv\\xmltv.exe", "tv_grab_es_miguiatv --configure"); //System.Diagnostics.Process.Start("xmltv\\xmltv.exe", "tv_grab_es_miguiatv --output hoy.xml --days 1"); // tv_grab_es_miguiatv [--config-file xmltv\\.xmltv\\tv_grab_es_miguiatv.conf] [--output FILE] [--days N] p.StartInfo.FileName = "xmltv\\xmltv.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.Arguments = " tv_grab_es_miguiatv --configure"; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.ErrorDialog = false; MensajeSistema(etRespuesta, "Comando: $ xmltv tv_grab_es_miguiatv --configure", kMensajeSistema.mCORRECTO); bool processStarted = p.Start(); if (processStarted) { inputWriter = p.StandardInput; outputReader = p.StandardOutput; errorReader = p.StandardError; inputWriter.WriteLine("yes"); inputWriter.WriteLine("yes"); inputWriter.WriteLine("all"); p.WaitForExit(); //Display the result string displayText = "Salida" + Environment.NewLine + "==============" + Environment.NewLine; displayText += outputReader.ReadToEnd(); displayText += errorReader.ReadToEnd(); MensajeSistema(etRespuesta, displayText, kMensajeSistema.mCORRECTO); MensajeSistema(etInfoXML, "Proceso finalizado", kMensajeSistema.mCORRECTO); gbInfoXML.Visible = true; } p.Close(); } catch (Exception ex) { MensajeSistema(etInfoXML, "Error al crear el proceso", kMensajeSistema.mERROR); gbInfoXML.Visible = true; } finally { if (inputWriter != null) { inputWriter.Close(); } if (outputReader != null) { outputReader.Close(); } if (errorReader != null) { errorReader.Close(); } if (p != null) { p.Close(); } btnConfigurar.Enabled = true; } }
private static bool BuildAndroidProject(string dir, string fileName) { try { EditorUtility.DisplayProgressBar("building apk", "ant clean", 0.1f); string path = dir + fileName; var antPath = Environment.GetEnvironmentVariable("ANT_HOME"); if (string.IsNullOrEmpty(antPath)) { Debug.Log("not found ant path in environment variable"); return(false); } #if UNITY_EDITOR_WIN string ant = antPath + "/bin/ant.bat"; #else string ant = antPath + "/bin/ant"; #endif using (var process = new System.Diagnostics.Process()) { process.StartInfo.FileName = ant; process.StartInfo.Arguments = "clean"; process.StartInfo.WorkingDirectory = path + "/" + PlayerSettings.productName; // 必须禁用操作系统外壳程序 process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.StandardOutputEncoding = Encoding.GetEncoding("gb2312"); process.Start(); Debug.Log("exec:" + ant + " arguments:" + process.StartInfo.Arguments); while (!process.StandardOutput.EndOfStream) { var str = process.StandardOutput.ReadLine(); Debug.Log(str); } process.WaitForExit(); process.Close(); } EditorUtility.DisplayProgressBar("building apk", "exec ant", 0.5f); using (var process = new System.Diagnostics.Process()) { process.StartInfo.FileName = ant; process.StartInfo.Arguments = EditorUserBuildSettings.development ? "debug" : "release"; process.StartInfo.WorkingDirectory = path + "/" + PlayerSettings.productName; // 必须禁用操作系统外壳程序 process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.StandardOutputEncoding = Encoding.GetEncoding("gb2312"); process.Start(); Debug.Log("exec:" + ant + " arguments:" + process.StartInfo.Arguments); float progress = 0.6f; while (!process.StandardOutput.EndOfStream) { var str = process.StandardOutput.ReadLine(); Debug.Log(str); progress += 0.001f; EditorUtility.DisplayProgressBar("building apk", str, progress); } process.WaitForExit(); process.Close(); } EditorUtility.DisplayProgressBar("building apk", "copy files", 0.8f); string apkFileName = fileName + (EditorUserBuildSettings.development ? "-debug" : "-release") + ".apk"; string apkPath = path + "/" + PlayerSettings.productName + "/bin/" + apkFileName; if (!File.Exists(apkPath)) { Debug.LogError("not found apk file:" + apkPath); return(false); } if (File.Exists(dir + apkFileName)) { File.Delete(dir + apkFileName); } Debug.Log("copy file from:" + apkPath + " to:" + dir + apkFileName); File.Copy(apkPath, dir + apkFileName); Directory.Delete(path, true); EditorUtility.DisplayProgressBar("building apk", "ant done", 1.0f); return(true); } catch (Exception e) { Debug.LogException(e); return(false); } }
private void btn_Run_Click(object sender, EventArgs e) { //입력창이 비어있는 경우 if (tb_MasterPath.TextLength == 0 || tb_SecondName.TextLength == 0 || tb_ThirdName.TextLength == 0) { MessageBox.Show("본클 경로 또는 2,3클 폴더 이름을 지정해주세요."); return; } //2클과 3클 이름이 같은 경우 if (tb_SecondName.Text == tb_ThirdName.Text) { MessageBox.Show("2클과 3클 폴더 이름을 각각 다르게 지정해주세요."); return; } //본클 경로가 거상 폴더가 아닌 경우 if (Directory.GetFiles(tb_MasterPath.Text, "Gersang.exe", SearchOption.TopDirectoryOnly).Length <= 0) { MessageBox.Show("제대로 된 거상 경로를 지정해주세요. (Gersang.exe 파일이 있는 경로)"); return; } ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(); Process p = new System.Diagnostics.Process(); psi.FileName = @"cmd"; psi.WorkingDirectory = tb_MasterPath.Text + @"\.."; psi.CreateNoWindow = true; psi.UseShellExecute = false; psi.RedirectStandardOutput = false; //IF WANT DEBUG, SET "TRUE" psi.RedirectStandardInput = true; psi.RedirectStandardError = true; p.StartInfo = psi; p.Start(); //CMD 구문 실행 (p는 AKInteractive 폴더에 머물러있는상태) Debug.WriteLine("CreateDirectory 진입 전"); CreateDirectory(ref p); Debug.WriteLine("CreateSymbolicLink 진입 전"); CreateSymbolicLink(ref p); // Thread.Sleep(500); Debug.WriteLine("CopyFile 진입 전"); CopyFile(); if (check_Shortcut.Checked) { Debug.WriteLine("CreateShortcut 진입 전"); CreateShortcut(); } Debug.WriteLine("CopyFile 또는 CreateShortcut 진입 종료"); p.StandardInput.Close(); p.WaitForExit(); p.Close(); //경로 및 폴더이름 저장 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["masterPath"].Value = tb_MasterPath.Text; config.AppSettings.Settings["secondName"].Value = tb_SecondName.Text; config.AppSettings.Settings["thirdName"].Value = tb_ThirdName.Text; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); // MessageBox.Show("생성 및 경로 저장 완료"); }
void OnDestroy() { CompilingProcess.Kill(); CompilingProcess.Close(); }
// Update is called once per frame void Update() { if (displaySettings != null) { displaySettings.Refresh(); if (displaySettings.HasExited == true) { displaySettings.Close(); displaySettings = null; } } //configuration utility, waiting for exit if (configUtility != null) { configUtility.Refresh(); //not sure if needed, check again. if (configUtility.HasExited == true) { Debug.Log("Configwindow Exited"); configUtility.Close(); //free up resources configUtility = null; //Debug.Log(MenuController.menuController.userSettings.isReload); MenuController.menuController.Load(); // loaded onto single menucontroller if (MenuController.menuController.userSettings.isReload == true) { // FileBrowser.HideDialog(true); //force close open file dialog //..apply new settings MenuController.menuController.userSettings.isReload = false; MenuController.menuController.isFirstTime = false; // since setting is saved, no need for notification dialogue. MenuController.menuController.Save(); // save isReload = false with the new data //...system tray update if (MenuController.menuController.userSettings.isDemo == true) //weather control { main.instance.WeatherMenuEnable(true); } else { main.instance.WeatherMenuEnable(false); } main.instance.SetStartup(MenuController.menuController.userSettings.runAtStartup); //checkmark btn if (MenuController.menuController.userSettings.runAtStartup == true) { main.instance.startup.Checked = true; } else { main.instance.startup.Checked = false; } if (MenuController.menuController.userSettings.vidPath != null) { vidScript.Stop_DXVA(); } main.instance.ClockCheckMark(); // update clock systray checkmark main.instance.ColorCheckMark(); //update ui button checkmark cycleScript.UnloadAssets(); //......restart scene, cleary memory. MenuController.menuController.LoadWeatherParameters(); //updated weather parameters. MenuController.menuController.Deserialize(MenuController.menuController.appList); //update application exclusion list SceneManager.LoadScene("wallpaper"); } } else { // Debug.Log("Running Process?"); } } else { //Debug.Log("PGM NULL"); } WallpaperChangeDetect(); }
/// <summary> /// Execute a shell command /// </summary> /// <param name="_FileToExecute">File/Command to execute</param> /// <param name="_CommandLine">Command line parameters to pass</param> /// <param name="_outputMessage">returned string value after executing shell command</param> /// <param name="_errorMessage">Error messages generated during shell execution</param> public void ExecuteShellCommand(string _FileToExecute, string _CommandLine, ref string _outputMessage, ref string _errorMessage) { // Set process variable // Provides access to local and remote processes and enables you to start and stop local system processes. System.Diagnostics.Process _Process = null; try { _Process = new System.Diagnostics.Process(); // invokes the cmd process specifying the command to be executed. string _CMDProcess = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\cmd.exe", new object[] { Environment.SystemDirectory }); // pass executing file to cmd (Windows command interpreter) as a arguments // /C tells cmd that we want it to execute the command that follows, and then exit. string _Arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/C {0}", new object[] { _FileToExecute }); // pass any command line parameters for execution if (_CommandLine != null && _CommandLine.Length > 0) { _Arguments += string.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", new object[] { _CommandLine, System.Globalization.CultureInfo.InvariantCulture }); } // Specifies a set of values used when starting a process. System.Diagnostics.ProcessStartInfo _ProcessStartInfo = new System.Diagnostics.ProcessStartInfo(_CMDProcess, _Arguments); // sets a value indicating not to start the process in a new window. _ProcessStartInfo.CreateNoWindow = true; // sets a value indicating not to use the operating system shell to start the process. _ProcessStartInfo.UseShellExecute = false; // sets a value that indicates the output/input/error of an application is written to the Process. _ProcessStartInfo.RedirectStandardOutput = true; _ProcessStartInfo.RedirectStandardInput = true; _ProcessStartInfo.RedirectStandardError = true; _Process.StartInfo = _ProcessStartInfo; // Starts a process resource and associates it with a Process component. _Process.Start(); // Instructs the Process component to wait indefinitely for the associated process to exit. _errorMessage = _Process.StandardError.ReadToEnd(); _Process.WaitForExit(); // Instructs the Process component to wait indefinitely for the associated process to exit. _outputMessage = _Process.StandardOutput.ReadToEnd(); _Process.WaitForExit(); } catch (Win32Exception _Win32Exception) { // Error Console.WriteLine("Win32 Exception caught in process: {0}", _Win32Exception.ToString()); } catch (Exception _Exception) { // Error Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } finally { // close process and do cleanup _Process.Close(); _Process.Dispose(); _Process = null; } }
private string RunSingleProcess(CommandExecutionParamModel model, int processTimeoutMs) { var process = new System.Diagnostics.Process(); var output = string.Empty; try { var outputBuilder = new StringBuilder(); ProcessStartInfo processStartInfo = new ProcessStartInfo { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardInput = true, RedirectStandardError = true, UseShellExecute = false, ErrorDialog = false, FileName = model.Command }; process.StartInfo = processStartInfo; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true; // attach the event handler for OutputDataReceived before starting the process process.OutputDataReceived += (sender, eventArgs) => outputBuilder.AppendLine(eventArgs.Data); process.ErrorDataReceived += (sender, eventArgs) => outputBuilder.AppendLine(eventArgs.Data); // start the process // then begin asynchronously reading the output // then wait for the process to exit // then cancel asynchronously reading the output process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (processTimeoutMs > 0) { var processExited = process.WaitForExit(processTimeoutMs); if (!processExited) { process.Kill(); throw new TimeoutException($"Process did not finish in {processTimeoutMs} ms."); } } else { process.WaitForExit(); } process.CancelOutputRead(); output = outputBuilder.ToString(); return(output); } catch (Exception e) { // Console.WriteLine(e.Message); throw; } finally { process.Close(); } }
// // With Ice >= 3.7.0 we get the compiler version from Ice.props // private String GetSliceCompilerVersion(String iceHome) { String sliceCompiler = GetSliceCompilerPath(null, iceHome); if (!File.Exists(sliceCompiler)) { String message = String.Format("'{0}' not found, review your Ice installation", sliceCompiler); OutputPane.OutputTaskItemString( message, EnvDTE.vsTaskPriority.vsTaskPriorityHigh, EnvDTE.vsTaskCategories.vsTaskCategoryBuildCompile, EnvDTE.vsTaskIcon.vsTaskIconCompile, sliceCompiler, 0, message); return(null); } System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = sliceCompiler; process.StartInfo.Arguments = "-v"; process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.WorkingDirectory = Path.GetDirectoryName(sliceCompiler); StreamReader reader = new StreamReader(); process.OutputDataReceived += new DataReceivedEventHandler(reader.appendData); try { process.Start(); // // When StandardError and StandardOutput are redirected, at least one // should use asynchronous reads to prevent deadlocks when calling // process.WaitForExit; the other can be read synchronously using ReadToEnd. // // See the Remarks section in the below link: // // http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx // // Start the asynchronous read of the standard output stream. process.BeginOutputReadLine(); // Read Standard error. string version = process.StandardError.ReadToEnd().Trim(); process.WaitForExit(); if (process.ExitCode != 0) { String message = String.Format("Slice compiler `{0}' failed to start(error code {1})", sliceCompiler, process.ExitCode); OutputPane.OutputTaskItemString( message, EnvDTE.vsTaskPriority.vsTaskPriorityHigh, EnvDTE.vsTaskCategories.vsTaskCategoryBuildCompile, EnvDTE.vsTaskIcon.vsTaskIconCompile, sliceCompiler, 0, message); return(null); } // // Convert beta version to is numeric value // if (version.EndsWith("b")) { version = String.Format("{0}.{1}", version.Substring(0, version.Length - 1), 51); } return(version); } catch (Exception ex) { String message = String.Format("An exception was thrown when trying to start the Slice compiler\n{0}", ex.ToString()); OutputPane.OutputTaskItemString( message, EnvDTE.vsTaskPriority.vsTaskPriorityHigh, EnvDTE.vsTaskCategories.vsTaskCategoryBuildCompile, EnvDTE.vsTaskIcon.vsTaskIconCompile, sliceCompiler, 0, message); return(null); } finally { process.Close(); } }
protected void Page_Load(object sender, EventArgs e) { configManager = new Config(Server.MapPath(VirtualPathUtility.GetDirectory(Request.Path))); if (configManager.getConfig("admin.password") != null && Session["FLEXPAPER_AUTH"] == null) { Response.Redirect("Default.aspx"); Response.End(); } if (Request["pdf2swfpath"] != null) { lpath_to_pdf2swf = Request["pdf2swfpath"]; } if (Request["pdf2jsonpath"] != null) { lpath_to_pdf2json = Request["pdf2jsonpath"]; } if (Request["dir"] != null) { if (Directory.Exists(Request["dir"]) && hasWriteAccessToFolder(Request["dir"])) { if (Request["pdfdir"] != null && Request["docsdir"] != null && Request["pdfdir"].ToString().Length > 0 && Request["docsdir"].ToString().Length > 0) { String docsdir = Request["docsdir"]; String pdfdir = Request["pdfdir"]; if (docsdir.LastIndexOf(@"\") != docsdir.Length - 1) { docsdir += @"\"; } if (pdfdir.LastIndexOf(@"\") != pdfdir.Length - 1) { pdfdir += @"\"; } try { if (!File.Exists(pdfdir + @"Paper.pdf")) { File.Copy(Server.MapPath(VirtualPathUtility.GetDirectory(Request.Path)) + @"\pdf\Paper.pdf", pdfdir + @"Paper.pdf"); } string command = configManager.getConfig("cmd.conversion.test"); command = command.Replace("{path.swftools}", lpath_to_pdf2swf); command = command.Replace("{path.pdf}", pdfdir); command = command.Replace("{path.swf}", docsdir); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = command.Substring(0, command.IndexOf(".exe") + 5); command = command.Substring(command.IndexOf(".exe") + 5); proc.StartInfo.Arguments = command; proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; if (proc.Start()) { proc.WaitForExit(); proc.Close(); if (File.Exists(docsdir + "flexpaper_test.swf")) { Response.Write("1"); } else { Response.Write("0"); Response.End(); } } else { Response.Write("-1"); } } catch (Exception ex) { Response.Write("-1"); } if (Request["testpdf2json"] != null && Request["testpdf2json"] == "True") { try { string command = configManager.getConfig("cmd.conversion.pdf2jsontest"); command = command.Replace("{path.pdf2json}", lpath_to_pdf2json); command = command.Replace("{path.pdf}", pdfdir); command = command.Replace("{path.swf}", docsdir); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = command.Substring(0, command.IndexOf(".exe") + 5); command = command.Substring(command.IndexOf(".exe") + 5); proc.StartInfo.Arguments = command; proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; if (proc.Start()) { proc.WaitForExit(); proc.Close(); if (File.Exists(docsdir + "flexpaper_test.js")) { Response.Write("1"); } else { Response.Write("0"); Response.End(); } } else { Response.Write("-2"); } } catch (Exception ex) { Response.Write("-2"); } } } else { Response.Write("1"); } } else { Response.Write("0"); Response.End(); } } }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Event handler. Called by btnGenerarXML for click events. </summary> /// /// <remarks> Evento que genera el fichero xml haciendo una llamada a XMLTV. </remarks> /// /// <param name="sender"> Source of the event. </param> /// <param name="e"> Event information. </param> //////////////////////////////////////////////////////////////////////////////////////////////////// private void btnGenerarXML_Click(object sender, EventArgs e) { System.Diagnostics.Process p = new System.Diagnostics.Process(); btnGenrarXML.Enabled = false; try { if (System.IO.File.Exists(".xmltv\\tv_grab_es_miguiatv.conf")) { MensajeSistema(etInfoXML, "Generando XML...", kMensajeSistema.mADVERTENCIA); gbInfoXML.Visible = true; // tv_grab_es_miguiatv [--config-file FILE] [--output FILE] [--days N] // ./.xmltv/tv_grab_es_miguiatv.conf p.StartInfo.FileName = "xmltv\\xmltv.exe"; p.StartInfo.UseShellExecute = true; p.StartInfo.Arguments = " tv_grab_es_miguiatv --output xmltv\\hoy.xml --days 1"; p.StartInfo.RedirectStandardInput = false; p.StartInfo.RedirectStandardOutput = false; p.StartInfo.RedirectStandardError = false; p.StartInfo.CreateNoWindow = false; p.StartInfo.ErrorDialog = false; // p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; MensajeSistema(etRespuesta, "Comando: $ xmltv tv_grab_es_miguiatv --output xmltv\\hoy.xml --days 1. \nEste proceso puede tardar varios minutos, por favor espere...", kMensajeSistema.mCORRECTO); bool processStarted = p.Start(); if (processStarted) { //Get the output stream //outputReader = p.StandardOutput; //errorReader = p.StandardError; p.Exited += new EventHandler(p_Exited); // Set 'EnableRaisingEvents' to true, to raise 'Exited' event when process is terminated. p.EnableRaisingEvents = true; p.WaitForExit(); //Display the result // string displayText = "Salida" + Environment.NewLine + "==============" + Environment.NewLine; // displayText += outputReader.ReadToEnd(); // displayText += Environment.NewLine + "Error" + Environment.NewLine + "==============" + // Environment.NewLine; // displayText += errorReader.ReadToEnd(); MensajeSistema(etRespuesta, "Fichero hoy.xml generado correctamente.", kMensajeSistema.mCORRECTO); MensajeSistema(etInfoXML, "Proceso finalizado", kMensajeSistema.mCORRECTO); gbInfoXML.Visible = true; } p.Close(); } else { if (MessageBox.Show("El fichero de configuración no existe. ¿Desea crearlo?", "TEVEO :: Aplicación de gestión", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { btnConfigurar_Click((Button)btnConfigurar, null); btnGenerarXML_Click((Button)btnGenrarXML, null); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (inputWriter != null) { inputWriter.Close(); } if (outputReader != null) { outputReader.Close(); } if (errorReader != null) { errorReader.Close(); } if (p != null) { p.Close(); } btnGenrarXML.Enabled = true; } }