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(); }
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 WhenProcessTimesOut_TaskIsCanceled() { // Arrange const int expectedExitCode = 123; const int millisecondsForTimeout = 3 * 1000; const int millisecondsToSleep = 5 * 1000; const int expectedStandardOutputLineCount = 5; const int expectedStandardErrorLineCount = 3; // Act var pathToConsoleApp = typeof(DummyConsoleApp.Program).Assembly.Location; var arguments = String.Join(" ", expectedExitCode, millisecondsToSleep, expectedStandardOutputLineCount, expectedStandardErrorLineCount); var startInfo = new ProcessStartInfo(pathToConsoleApp, arguments); var cancellationToken = new CancellationTokenSource(millisecondsForTimeout).Token; var task = ProcessEx.RunAsync(startInfo, cancellationToken); // Assert Assert.IsNotNull(task); try { var results = task.Result; Assert.Fail("Timeout did not occur"); } catch (AggregateException aggregateException) { // expected Assert.AreEqual(1, aggregateException.InnerExceptions.Count); var innerException = aggregateException.InnerExceptions.Single(); Assert.IsInstanceOfType(innerException, typeof(OperationCanceledException)); var canceledException = innerException as OperationCanceledException; Assert.IsNotNull(canceledException); Assert.IsTrue(cancellationToken.IsCancellationRequested); } Assert.AreEqual(TaskStatus.Canceled, task.Status); }
public DisassembleResult Disassemble(string compiledFilePath, string additionalArguments = null) { if (!File.Exists(compiledFilePath)) { throw new ArgumentException( $"Compiled file not found in: {compiledFilePath}.", nameof(compiledFilePath)); } var workingDirectory = new FileInfo(this.DisassemblerPath).DirectoryName; var arguments = this.BuildDisassemblerArguments(compiledFilePath, additionalArguments); var disassemblerProcessStartInfo = new ProcessStartInfo(this.DisassemblerPath) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, WorkingDirectory = workingDirectory, Arguments = arguments }; this.UpdateDisassemblerProcessStartInfo(disassemblerProcessStartInfo); string disassambledCode; var isDisassembledSuccessfully = this.ExecuteDisassemblerProcess(disassemblerProcessStartInfo, out disassambledCode); return new DisassembleResult(isDisassembledSuccessfully, disassambledCode); }
public static ProcessStartInfo CreateTestAndCoverageProcessStartInfo(Settings settings, string[] fileNames) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; startInfo.FileName = @"""" + settings.PartCoverPath + @""""; startInfo.Arguments += " --target "; startInfo.Arguments += @"""" + settings.MSTestPath + @""""; startInfo.Arguments += " --target-work-dir "; startInfo.Arguments += @"""" + settings.OutputPath + @""""; // trim trailing slash? startInfo.Arguments += " --target-args "; startInfo.Arguments += @""""; foreach (string fileName in fileNames) { FileInfo f = new FileInfo(fileName); startInfo.Arguments += " /testcontainer:"; startInfo.Arguments += f.Name; } startInfo.Arguments += " /noisolation"; startInfo.Arguments += " /nologo"; startInfo.Arguments += " /resultsfile:"; startInfo.Arguments += settings.TestLogFileName; startInfo.Arguments += @""""; startInfo.Arguments += " --include " + settings.CoverageReportingAssembliesRegEx; startInfo.Arguments += " --output " + @"""" + Path.Combine(settings.OutputPath, settings.CoverageLogFileName) + @""""; return startInfo; }
/// <summary> /// 检查是否是管理员身份 /// </summary> private void CheckAdministrator() { var wi = WindowsIdentity.GetCurrent(); var wp = new WindowsPrincipal(wi); bool runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator); if (!runAsAdmin) { // It is not possible to launch a ClickOnce app as administrator directly, // so instead we launch the app as administrator in a new process. var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase); // The following properties run the new process as administrator processInfo.UseShellExecute = true; processInfo.Verb = "runas"; // Start the new process try { Process.Start(processInfo); } catch { MessageBox.Show("没有管理员权限\n请右键该程序之后点击“以管理员权限运行”"); } // Shut down the current process Environment.Exit(0); } }
public string Create(OpValue[] prog) { string ePath = Path.GetTempFileName(); ProcessStartInfo info = new ProcessStartInfo("gcc", "-O2 -x c -o " + ePath + " -") { RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = true }; using (var process = Process.Start(info)) { process.StandardInput.WriteLine(Pre); foreach (OpValue op in prog) { this.Append(process.StandardInput, op); } process.StandardInput.WriteLine(Post); process.StandardInput.Flush(); process.StandardInput.Close(); process.WaitForExit(); } return ePath; }
/// <summary> /// Execute a general git command /// </summary> /// <param name="args">The command arguments</param> /// <returns>A list of strings with the command output</returns> public List<string> ExecCommand(string args) { //Console.WriteLine("gitPath = "+GitPath); //Console.WriteLine("args = " + args); ProcessStartInfo psinfo = new ProcessStartInfo { FileName = GitPath, Arguments = args, UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; Stdout = new List<string>();// clear the buffer. Stderr = new List<string>(); using (Process gitProcess = new Process()) { gitProcess.StartInfo = psinfo; gitProcess.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived); bool started = gitProcess.Start(); gitProcess.BeginOutputReadLine(); gitProcess.WaitForExit(); gitProcess.Close(); return Stdout; }; }
/// <summary> /// 保存XPS文件到PDF文件 /// </summary> /// <param name="xpsPath"></param> /// <param name="pdfFilePath"></param> public static void SavePDFFile(string xpsPath, string pdfFilePath) { if (File.Exists(xpsPath)) { //pdfFilePath = this.GetContainerPathFromDialog(); var excuteDll = Path.Combine(System.Environment.CurrentDirectory, "gxpswin32.exe"); ProcessStartInfo gxpsArguments = new ProcessStartInfo(excuteDll, String.Format("-sDEVICE=pdfwrite -sOutputFile={0} -dNOPAUSE {1}", "\"" + pdfFilePath + "\"", "\"" + xpsPath + "\"")); gxpsArguments.WindowStyle = ProcessWindowStyle.Hidden; using (var gxps = Process.Start(gxpsArguments)) { gxps.WaitForExit(); } if (File.Exists(xpsPath)) { File.Delete(xpsPath);//删除临时文件 } } else { MessageBox.Show("The file not find."); } }
private static void Exec(string command) { if (!string.IsNullOrEmpty(command)) { try { ProcessStartInfo lProc = new ProcessStartInfo(); lProc.UseShellExecute = false; lProc.CreateNoWindow = true; if (command.Contains(" ")) { lProc.FileName = command.Substring(0, command.IndexOf(' ')); lProc.Arguments = command.Substring(command.IndexOf(' ')); } else { lProc.FileName = command; } Process.Start(lProc); } catch (Exception e) { Console.WriteLine(e); MessageBox.Show("Unable to execute command \"" + command + "\": " + e); } } }
private static string InvokeAndReturnOutput(string input, string output_exe) { String dir = Directory.GetCurrentDirectory(); dir += @"\" + output_exe; ProcessStartInfo Invoke = new ProcessStartInfo(dir); Invoke.UseShellExecute = false; Invoke.CreateNoWindow = false; Invoke.RedirectStandardError = true; Invoke.RedirectStandardOutput = true; try { Process InvokeEXE = Process.Start(Invoke); StreamReader sr = InvokeEXE.StandardOutput; StreamReader sr2 = InvokeEXE.StandardError; string output = sr.ReadToEnd(); string output2 = sr2.ReadToEnd(); sr.Close(); sr2.Close(); InvokeEXE.Close(); if (output2 != string.Empty) { DeleteEmittedExe(output_exe); return output2; } DeleteEmittedExe(output_exe); return output; } catch (Exception e) { DeleteEmittedExe(output_exe); return e.Message; } }
private bool runScript(string arguments, string workingDir, string successText, string errMsg) { try { ProcessStartInfo psi = new ProcessStartInfo(@"cscript", @"ospp.vbs " + arguments); psi.RedirectStandardOutput = true; psi.UseShellExecute = false; psi.WorkingDirectory = workingDir; Process pc = new Process(); pc.StartInfo = psi; pc.Start(); outputTextBox.Text = pc.StandardOutput.ReadToEnd(); if (!outputTextBox.Text.Contains(successText)) { if(errMsg != null) MessageBox.Show(errMsg, @"錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } catch (Exception gg) { MessageBox.Show(gg.Message); } return true; }
static void Main() { mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName, out created); if (created) { //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //Application.ThreadException += Application_ThreadException; //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // As all first run initialization is done in the main project, // we need to make sure the user does not start a different knot first. if (CfgFile.Get("FirstRun") != "0") { try { ProcessStartInfo process = new ProcessStartInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\FreemiumUtilities.exe"); Process.Start(process); } catch (Exception) { } Application.Exit(); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } }
static void Main() { string[] arguments = Environment.GetCommandLineArgs(); foreach (string argument in arguments) { // Uninstall if (argument.Split(new char[] { '=' })[0].ToLower() == "/u") { string guid = argument.Split(new char[] { '=' })[1]; string path = Environment.GetFolderPath(Environment.SpecialFolder.System); if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\Picasa Wallpaper Changer.lnk")) { System.IO.File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\Picasa Wallpaper Changer.lnk"); } ProcessStartInfo si = new ProcessStartInfo(path + "\\msiexec.exe", "/i " + guid); Process.Start(si); Application.Exit(); return; } } // start the app Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Controller()); }
public void CalculatorTests() { //strat process for the above exe file location var psi = new ProcessStartInfo(ExeSourceFile); // launch the process through white application using (var application = Application.AttachOrLaunch(psi)) using (var mainWindow = application.GetWindow(SearchCriteria.ByText("Calculator"), InitializeOption.NoCache)) { // Verify can click on menu twice var menuBar = mainWindow.Get<MenuBar>(SearchCriteria.ByText("Application")); menuBar.MenuItem("Edit", "Copy").Click(); menuBar.MenuItem("Edit", "Copy").Click(); mainWindow.Keyboard.HoldKey(KeyboardInput.SpecialKeys.CONTROL); mainWindow.Keyboard.Enter("E"); mainWindow.Keyboard.LeaveKey(KeyboardInput.SpecialKeys.CONTROL); //On Date window find the difference between dates. //Set value into combobox mainWindow.Get<ComboBox>(SearchCriteria.ByAutomationId("4003")).Select("Calculate the difference between two dates"); //Click on Calculate button mainWindow.Get<Button>(SearchCriteria.ByAutomationId("4009")).Click(); mainWindow.Keyboard.HoldKey(KeyboardInput.SpecialKeys.CONTROL); mainWindow.Keyboard.PressSpecialKey(KeyboardInput.SpecialKeys.F4); mainWindow.Keyboard.LeaveKey(KeyboardInput.SpecialKeys.CONTROL); var menuView = mainWindow.Get<Menu>(SearchCriteria.ByText("View")); menuView.Click(); var menuViewBasic = mainWindow.Get<Menu>(SearchCriteria.ByText("Basic")); menuViewBasic.Click(); PerformSummationOnCalculator(mainWindow); } }
public Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationTokenSource cancellationToken) { processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; var tcs = new TaskCompletionSource<ProcessResults>(); var standardOutput = new List<string>(); var standardError = new List<string>(); var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; process.OutputDataReceived += (sender, args) => { if (args.Data != null) { standardOutput.Add(args.Data); } }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) { standardError.Add(args.Data); } }; cancellationToken.Token.ThrowIfCancellationRequested(); _log.Debug("Registering cancellation for " + cancellationToken.GetHashCode()); cancellationToken.Token.Register(() => { tcs.TrySetCanceled(); KillProcessAndChildren(process.Id); }); process.Exited += (sender, args) => { tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError)); }; if (process.Start() == false) { tcs.TrySetException(new InvalidOperationException("Failed to start process")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); return tcs.Task; }
bool runLoginScript() { using (Process p = new Process()) { ProcessStartInfo info = new ProcessStartInfo(@"ruby"); info.Arguments = "C:\\Users\\Saulo\\Documents\\RPGVXAce\\projectNOMAD\\Scripts\\login.rb" +" "+ username + " " + password; // set args info.RedirectStandardInput = true; info.RedirectStandardOutput = true; info.UseShellExecute = false; p.StartInfo = info; p.Start(); String output = p.StandardOutput.ReadToEnd(); // process output if (output == "0") { MessageBox.Show("Incorrect password or username"); return false; } else { MessageBox.Show("Welcome!"); return true; } } }
public static void HandleDoProcessStart(Packets.ServerPackets.DoProcessStart command, Client client) { if (string.IsNullOrEmpty(command.Processname)) { new Packets.ClientPackets.SetStatus("Process could not be started!").Execute(client); return; } try { ProcessStartInfo startInfo = new ProcessStartInfo { UseShellExecute = true, FileName = command.Processname }; Process.Start(startInfo); } catch { new Packets.ClientPackets.SetStatus("Process could not be started!").Execute(client); } finally { HandleGetProcesses(new Packets.ServerPackets.GetProcesses(), client); } }
public static void Uninstall(string manifestFile, string targetDirectory) { string targetPath = Path.Combine(targetDirectory, Path.GetFileName(manifestFile)); File.Copy(manifestFile, targetPath); ProcessStartInfo psi = new ProcessStartInfo(); psi.Arguments = "/m:" + targetPath; psi.Verb = "runas"; psi.CreateNoWindow = true; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.FileName = UNINST_APP_NAME; string errors; string output; using (Process p = Process.Start(psi)) { output = p.StandardOutput.ReadToEnd(); errors = p.StandardError.ReadToEnd(); } if (errors.Trim() != string.Empty) throw new Exception("Failure: " + errors); Console.Write(output); File.Delete(targetPath); }
static void Main(string[] args) { List<string> startApps = new List<string>(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new frmMain()); foreach (string s in args) { if (s.Split(' ').Count() > 1) { } if (File.Exists(s)) { startApps.Add(s); } } foreach (string s in startApps) { ProcessStartInfo psi = new ProcessStartInfo(s); psi.RedirectStandardOutput = true; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.CreateNoWindow = true; psi.UseShellExecute = false; Process run; run = Process.Start(psi); System.IO.StreamReader myOutput = run.StandardOutput; //MessageBox.Show("Running " + s); run.WaitForExit(2000); } }
public static IEnumerable<string> GetGitOnelineLogs(string path, string currentBranch) { var num = currentBranch.Split('/')[1]; var info = new ProcessStartInfo("git", "log --oneline --grep=\"refs #\"" + num + "$") { WorkingDirectory = path, RedirectStandardOutput = true, StandardOutputEncoding = Encoding.UTF8, CreateNoWindow = true, UseShellExecute = false }; try { using (var proc = Process.Start(info)) { var log = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); return log.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); } } catch { return new string[0]; } }
private void buttonPull_Click(object sender, EventArgs e) { string searchString = ""; si = new ProcessStartInfo("cmd.exe"); si.RedirectStandardInput = true; si.RedirectStandardOutput = true; si.RedirectStandardError = true; si.UseShellExecute = false; si.CreateNoWindow = true; si.WindowStyle = ProcessWindowStyle.Hidden; Process console = Process.Start(si); this.toolStripStatusLabel1.Text = "WARNING: disconnecting device from USB will stop the pulling process!!"; for (int i = 0; i < checkedListBoxLocations.CheckedItems.Count; i++) { searchString = "adb pull \"" + checkedListBoxLocations.CheckedItems[i] + "\" \"" + saveLoc + "\""; console.StandardInput.WriteLine(searchString); } console.StandardInput.WriteLine("exit"); while (!console.HasExited){} //Wait for all files to be pulled! this.toolStripStatusLabel1.Text = "It is now ok to disconnect device from USB."; }
public IProcess CreateProcess(ProcessStartInfo startInfo) { if (MockCreateProcess_StartInfo == null) throw new NotImplementedException(); return MockCreateProcess_StartInfo(startInfo); }
/// <summary> /// Authorizes the server. /// </summary> /// <param name="httpServerPort">The HTTP server port.</param> /// <param name="httpServerUrlPrefix">The HTTP server URL prefix.</param> /// <param name="webSocketPort">The web socket port.</param> /// <param name="udpPort">The UDP port.</param> /// <param name="tempDirectory">The temp directory.</param> public static void AuthorizeServer(int httpServerPort, string httpServerUrlPrefix, int webSocketPort, int udpPort, string tempDirectory) { // Create a temp file path to extract the bat file to var tmpFile = Path.Combine(tempDirectory, Guid.NewGuid() + ".bat"); // Extract the bat file using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(ServerAuthorization).Namespace + ".RegisterServer.bat")) { using (var fileStream = File.Create(tmpFile)) { stream.CopyTo(fileStream); } } var startInfo = new ProcessStartInfo { FileName = tmpFile, Arguments = string.Format("{0} {1} {2} {3}", httpServerPort, httpServerUrlPrefix, udpPort, webSocketPort), CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, Verb = "runas", ErrorDialog = false }; using (var process = Process.Start(startInfo)) { process.WaitForExit(); } }
/// <summary> /// Ensures that an instance of Reflector is running and connects to it. /// </summary> /// <returns>The <see cref="IReflectorService"/> that can be used to control the running instance of Reflector.</returns> public static IntPtr FindOrStartReflector() { IntPtr hwnd = FindReflector(); if (hwnd != IntPtr.Zero) return hwnd; // Get Reflector path and set it up string reflectorExeFullPath = WorkbenchSingleton.SafeThreadFunction<string>(ReflectorSetupHelper.GetReflectorExeFullPathInteractive); if (reflectorExeFullPath == null) return IntPtr.Zero; // start Reflector ProcessStartInfo psi = new ProcessStartInfo(reflectorExeFullPath); psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName); using (Process p = Process.Start(psi)) { try { p.WaitForInputIdle(10000); } catch (InvalidOperationException) { // can happen if Reflector is configured to run elevated } } for (int retryCount = 0; retryCount < 10; retryCount++) { hwnd = FindReflector(); if (hwnd != IntPtr.Zero) { return hwnd; } Thread.Sleep(500); } MessageService.ShowError("${res:ReflectorAddIn.ReflectorRemotingFailed}"); return IntPtr.Zero; }
public static Tuple<String, String>[] QueryFileDescriptor(string search, string args="") { Process process = null; ProcessStartInfo processStartInfo = null; if (NUtilityGlobalContext.OSType == (int)NUtilityGlobalContext.OS.Windows) { if (HasHandleExe()) { } else { MainWindow.PrintMessageInMessageBoxInst("Cannot find handle.exe! Make sure that it exists", severity: (int)MainWindow.TextSeverity.ERROR); return null; } } else if (NUtilityGlobalContext.OSType == (int)NUtilityGlobalContext.OS.Linux) { // Use lsof processStartInfo = new ProcessStartInfo("lsof"); processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardError = true; processStartInfo.RedirectStandardOutput = true; } else if (NUtilityGlobalContext.OSType == (int)NUtilityGlobalContext.OS.OSX) { // Use lsof processStartInfo = new ProcessStartInfo("lsof"); } return null; }
private static void Execute(string arguments, out string standardOutput, out string standardError) { ProcessStartInfo pi = new ProcessStartInfo( Path.Combine(General.AzureSDKBinFolder, Resources.CsPackExe), arguments); ProcessHelper.StartAndWaitForProcess(pi, out standardOutput, out standardError); }
static int SourceRevision(string folder, out bool hasmodifications, string arguments) { hasmodifications = false; ProcessStartInfo pi = new ProcessStartInfo(); pi.RedirectStandardOutput = true; pi.WorkingDirectory = folder; pi.FileName = "svnversion"; pi.Arguments = arguments; pi.CreateNoWindow = true; pi.UseShellExecute = false; Process proc = System.Diagnostics.Process.Start(pi); int version = 0; while (!proc.StandardOutput.EndOfStream) { string[] vals = proc.StandardOutput.ReadLine().Split(':'); string line = vals[vals.Length - 1]; if (line.EndsWith("M", StringComparison.OrdinalIgnoreCase)) { hasmodifications = true; } int.TryParse(line.Trim('M'), out version); } proc.WaitForExit(); if (version == 0) { throw new ApplicationException("Can't parse svnversion output"); } if (hasmodifications) version++; return version; }
/// <summary> /// Used to start a subprocess. This method handles Ctrl+C and cancels the child process before exiting. /// </summary> /// <param name="psi">information for the process to be started</param> /// <param name="afterExecution">delegate, in case of success</param> /// <param name="executionError">delegate, in case of error</param> private static void executeProcess(ProcessStartInfo psi, afterExecutionHandler afterExecution = null, executionErrorHandler executionError = null) { try { using (Process process = Process.Start(psi)) { ConsoleCancelEventHandler handler = (object o, ConsoleCancelEventArgs a) => { if (process != null && !process.HasExited) try { CommandLineOptions.instance.Debug(1, "Exiting, but process didn't finish yet. Killing it."); process.Kill(); } catch { } }; Console.CancelKeyPress += handler; process.WaitForExit(); Console.CancelKeyPress -= handler; if (afterExecution != null) afterExecution(process); } } catch (Exception e) { if (executionError != null) executionError(e); } }
public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken) { if (processStartInfo == null) { throw new ArgumentNullException("processStartInfo"); } // force some settings in the start info so we can capture the output processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; processStartInfo.CreateNoWindow = true; var tcs = new TaskCompletionSource<ProcessResults>(); var standardOutput = new List<string>(); var standardError = new List<string>(); var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true, }; process.OutputDataReceived += (sender, args) => { if (args.Data != null) { standardOutput.Add(args.Data); } }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) { standardError.Add(args.Data); } }; process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError)); cancellationToken.Register(() => { tcs.TrySetCanceled(); process.CloseMainWindow(); }); cancellationToken.ThrowIfCancellationRequested(); if (process.Start() == false) { tcs.TrySetException(new InvalidOperationException("Failed to start process")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); return tcs.Task; }
void CancelGradleBuild() { Process cancelGradleProcess = new Process(); string arguments = "-Xmx1024m -classpath \"" + gradlePath + "\" org.gradle.launcher.GradleMain --stop"; var processInfo = new System.Diagnostics.ProcessStartInfo { WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal, FileName = jdkPath, Arguments = arguments, RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true, }; cancelGradleProcess.StartInfo = processInfo; cancelGradleProcess.EnableRaisingEvents = true; cancelGradleProcess.OutputDataReceived += new DataReceivedEventHandler( (s, e) => { if (e != null && e.Data != null && e.Data.Length != 0) { UnityEngine.Debug.LogFormat("Gradle: {0}", e.Data); } } ); apkOutputSuccessful = false; cancelGradleProcess.Start(); cancelGradleProcess.BeginOutputReadLine(); cancelGradleProcess.WaitForExit(); buildFailed = true; }
public void OnTimer(object sender, ElapsedEventArgs args) { Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; // If the data dir does not exist, the user must restart the service OR restore the directory. // If the last run record does not exist, it will be recreated. if (System.IO.Directory.Exists(Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\\badcert"))) { if (!System.IO.File.Exists(Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\\badcert\\last-run"))) { System.IO.File.WriteAllText(Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\\badcert\\last-run"), "0"); } string lastRunFileContent = System.IO.File.ReadAllText(Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\\badcert\\last-run")); if (Convert.ToInt32(lastRunFileContent) + updateInterval < unixTimestamp) { using (var client = new WebClient()) { client.DownloadFile("https://raw.githubusercontent.com/yihanwu1024/badcert/master/badcerts.p7b", Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\\badcert\\badcerts.p7b")); } #region Run certutil command to install certificates System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/C certutil -addstore -ent Disallowed " + Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\\badcert\\badcerts.p7b"); process.StartInfo = startInfo; process.Start(); #endregion System.IO.File.WriteAllText(Environment.ExpandEnvironmentVariables("%PROGRAMDATA%\\badcert\\last-run"), Convert.ToString(unixTimestamp)); } } }
public void Start() { if (_server == null) { _server = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(ExecutablePath) { CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false }; _server.StartInfo = si; _server.ErrorDataReceived += _server_ErrorDataReceived; _server.OutputDataReceived += _server_OutputDataReceived; } _isStarted = _server.Start(); _inputWriter = _server.StandardInput; _server.BeginOutputReadLine(); _server.BeginErrorReadLine(); }
public static string ExecuteBat(this System.Diagnostics.Process process, string batToExecute) { string path = Path.GetRandomFileName() + ".bat"; StreamWriter swBat = File.CreateText(path); StringBuilder informacion = new StringBuilder(); StreamReader str; swBat.Write(batToExecute); swBat.Close(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = path; startInfo.Hide(); process.StartInfo = startInfo; process.Start(); str = process.StandardOutput; while (!str.EndOfStream) { informacion.Append((char)str.Read()); } str.Close(); File.Delete(path); return(informacion.ToString().Substring(informacion.ToString().IndexOf('>') + batToExecute.Length + 4)); }
private void generarImagen(string nombre, string ruta) { try { var command = string.Format("dot -Tpng " + this.ruta + nombre + " -o {1}", Path.Combine(ruta, nombre), Path.Combine(ruta, nombre.Replace(".dot", ".png"))); var procStarInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/C " + command); var proc = new System.Diagnostics.Process(); proc.StartInfo = procStarInfo; proc.Start(); proc.WaitForExit(); //MessageBox.Show("Imagen creada sin problemas", "Información"); } catch (Exception e) { mensaje.setMensaje("No se pudo generar la imagen del grafo"); } }
/// <summary> /// 截取视频 /// </summary> /// <param name="src">视频源文件</param> /// <param name="dest">目标文件</param> /// <param name="Begin">开始截取时间(秒)</param> /// <param name="Length">截取长度</param> /// <returns>成功返回真,失败返回假 </returns> public static bool Intercept(string src, string dest, double Begin, TimeSpan Length, Quality Quality) { if (!System.IO.File.Exists(FfmpegPath)) { throw new Exception("Ffmpeg not found: " + FfmpegPath); } if (!System.IO.File.Exists(src)) { throw new Exception("The video file is not exist: " + src); } System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(FfmpegPath); FilestartInfo.Arguments = String.Format("-i \"{0}\" " + Args[Convert.ToInt32(Quality)] + " -ss {1} -t {2} \"{3}\"", src, Begin, Length, dest); try { var proc = System.Diagnostics.Process.Start(FilestartInfo); proc.WaitForExit(); } catch { return(false); } return(true); }
public Boolean GetRFXML() { Console.WriteLine("Program start fetching recent file history from the system..."); String command = "/sxml temp.xml"; System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "RecentFilesView.exe"; startInfo.Arguments = "/C " + command; //startInfo.Arguments = command; process.StartInfo = startInfo; try { process.Start(); } catch { return(false); } Console.WriteLine("Fetching Finished..."); return(true); }
//private void activate3DBuilder() //{ // //run CSNamedPipe.exe // runCSNamedPipe(); // //run 3DBuilder.exe // run3DBuilder(); // /*Ben test // //originating from ALHomePage.aspx // StreamWriter wr = (StreamWriter)Session["Writer"]; // //Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script type='text/javascript'>alert('" + os.StartInfo.RedirectStandardInput + os.Id + "');</script>"); // //StreamWriter wr = os.StandardInput; // wr.WriteLine("1 2"); // */ //} //private void runCSNamedPipe() //{ // //originating from Default.aspx // Process os = new Process(); // string hintID = "5555";//this hintID is hard-coded by 昇宏學長 // os.StartInfo.WorkingDirectory = Request.MapPath("~/"); // os.StartInfo.FileName = Request.MapPath("App_Code/CSNamedPipe/bin/Debug/CSNamedPipe.exe"); // os.StartInfo.UseShellExecute = false; // os.StartInfo.RedirectStandardInput = true; // /* // os.StartInfo.Arguments = hintID; // */ // //pass Hints's userID to CSNamedPipe.exe as the name of the namedPipe. // os.StartInfo.Arguments = strUserID; // os.Start(); // StreamWriter wr = os.StandardInput; // //os.StandardInput.Close(); // Session["Writer"] = wr; // Session["Process"] = os; // //get process ID of the CSNamedPipe, and store it in a session var so that we can kill the CSNamedPipe process after the user finishes using the connection with 3DBuilder // Session["ProcessID"] = os.Id.ToString(); //} private void run3DBuilder() { //this works but 3DBuilder will be run in background System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.Verb = "runas"; startInfo.WorkingDirectory = Request.MapPath("~/"); /* * startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; * startInfo.CreateNoWindow = true; */ startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; startInfo.CreateNoWindow = false; startInfo.UseShellExecute = true; startInfo.FileName = Request.MapPath("3DBuilder.lnk"); //startInfo.FileName = "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\installutil.exe"; //startInfo.Arguments = "D:\\Projects\\MyNewService\\bin\\Release\\MyNewService.exe"; process.StartInfo = startInfo; bool processStarted = process.Start(); }
/// <summary> /// 尝试将一个视频文件转换格式并压缩 /// </summary> /// <param name="src">视频源文件</param> /// <param name="dest">目标文件</param> /// <param name="width">宽度(px)</param> /// <param name="height">高度(px)</param> /// <returns></returns> public static bool FormatConvert(string src, string dest, int width, int height, Quality Quality) { if (!System.IO.File.Exists(FfmpegPath)) { throw new Exception("Ffmpeg not found: " + FfmpegPath); } if (!System.IO.File.Exists(src)) { throw new Exception("The video file is not exist: " + src); } System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(FfmpegPath); FilestartInfo.Arguments = " -i \"" + src + "\" " + Args[Convert.ToInt32(Quality)] + " -s " + width + "x" + height + " \"" + dest + "\""; try { var proc = System.Diagnostics.Process.Start(FilestartInfo); proc.WaitForExit(); } catch { return(false); } return(true); }
public Streaming video(string nombre) { string sesion; Camara vidcam = new Camara(); vidcam= Camaras.Find(e => e.nombre.Equals(nombre)); Streaming nes = new Streaming(); nes.protocolo = "udp"; nes.ip = "192.168.1.11"; nes.puerto = Convert.ToString(puerto); puerto++; nes.dominio = nombre; nes.ffplay = "ffplay " + nes.protocolo + "://" + nes.ip + ":" + nes.puerto + "/" + nes.dominio; sesion = "ffmpeg -i http://"+vidcam.usuario+":"+vidcam.contraseña+"@"+vidcam.ip+"/video/mjpg.cgi -f mpegts "+nes.protocolo+"://"+nes.ip+":"+nes.puerto+"/"+nes.dominio; System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo("CMD.EXE", "/C" + sesion); //info.Verb = "open"; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; System.Diagnostics.Process.Start(info); return nes; }
private int runDaemons(string pFileName, string pArgName) { /* * Taken from: * http://stackoverflow.com/questions/1271938/how-to-run-batch-file-from-c-sharp-in-the-background * http://stackoverflow.com/questions/1585354/get-return-value-from-process */ ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(); si.CreateNoWindow = true; si.FileName = pFileName; if (pArgName != "") { si.Arguments = " " + pArgName; } si.UseShellExecute = false; Process p = System.Diagnostics.Process.Start(si); p.WaitForExit(); int retval = p.ExitCode; return(retval); }
public static void Start(string executablePath, bool isHidden = false, bool _isAdmin = false) { System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = _workingDirectory; startInfo.FileName = executablePath; if (isHidden) { startInfo.WindowStyle = ProcessWindowStyle.Hidden; } //设置启动动作,确保以管理员身份运行 if (_isAdmin) { startInfo.Verb = "runas"; } try { System.Diagnostics.Process.Start(startInfo); } catch (Exception) { } }
[WebMethod] // Crea Imagen de archivo Dot public void crearPng(string nombre) { crearPngP(nombre); //Indicamos que deseamos inicializar el proceso cmd.exe junto a un comando de arranque. //(/C, le indicamos al proceso cmd que deseamos que cuando termine la tarea asignada se cierre el proceso). //Para mas informacion consulte la ayuda de la consola con cmd.exe /? string comando = "dot -Tpng C:\\inetpub\\wwwroot\\ProyectoEDD\\EDD\\" + nombre + ".dot -o C:\\inetpub\\wwwroot\\ProyectoEDD\\EDD\\" + nombre + ".png"; System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + comando); // Indicamos que la salida del proceso se redireccione en un Stream procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; //Indica que el proceso no despliegue una pantalla negra (El proceso se ejecuta en background) procStartInfo.CreateNoWindow = false; //Inicializa el proceso System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); //Consigue la salida de la Consola(Stream) y devuelve una cadena de texto string result = proc.StandardOutput.ReadToEnd(); //Muestra en pantalla la salida del Comando //Console.WriteLine(result); }
public static void Execute(string exe, string arg, string directory = "") { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = exe; startInfo.Arguments = arg; //startInfo.UseShellExecute = false; //startInfo.RedirectStandardOutput = true; if (directory != "") { startInfo.WorkingDirectory = directory; } process.StartInfo = startInfo; process.Start(); //while (!process.StandardOutput.EndOfStream) // Console.WriteLine(process.StandardOutput.ReadLine()); process.WaitForExit(); }
private static void ExecuteProcess(bool openZI) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); #if UNITY_EDITOR_WIN string commandToSend = openZI ? System.String.Format("/c {0}/labdriver -o {1} -pretty go-zi-module", UnityEditor.Lumin.UserBuildSettings.SDKPath, _LogFile) : System.String.Format("/c {0}/labdriver -o {1} -pretty start-gui", UnityEditor.Lumin.UserBuildSettings.SDKPath, _LogFile); startInfo.FileName = "CMD.exe"; startInfo.UseShellExecute = true; #elif UNITY_EDITOR_OSX string commandToSend = openZI ? System.String.Format("{0}/labdriver -o {1} -pretty go-zi-module", UnityEditor.Lumin.UserBuildSettings.SDKPath, _LogFile) : System.String.Format("{0}/labdriver -o {1} -pretty start-gui", UnityEditor.Lumin.UserBuildSettings.SDKPath, _LogFile); startInfo.FileName = "/bin/bash"; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; #endif startInfo.CreateNoWindow = true; startInfo.Arguments = commandToSend; startInfo.WindowStyle = ProcessWindowStyle.Hidden; process.EnableRaisingEvents = true; process.Exited += OnProcessExit; process.StartInfo = startInfo; process.Start(); }
public static void SplitAdr() { try { _report = "\n\n\t Разбивка адресов..."; ReportUpdated?.Invoke(_report); SplitCompletHandler += UpdateReport; ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo(@"x:\utils\AdressSpliter\Adr\Adr\bin\Debug\Adr.exe"); if (QMediator.PathToRegDest != null) { pInfo.Arguments = ("\"" + QMediator.PathToRegDest + "\""); } Process process = Process.Start(pInfo); process.EnableRaisingEvents = true; process.Exited += SplitFinished; } catch (Exception ex) { ExceptionHandler("SplitAdr()", ex.Message); } }
//private void button2_Click(object sender, EventArgs e) //{ // keybd_event((byte)Keys.SelectMedia, 0, 0, 0); //} private void ehshall_start() { //声明一个程序类 System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo(); //设置外部程序名 Info.FileName = "C:\\Windows\\ehome\\ehshell.exe"; //声明一个程序类 System.Diagnostics.Process Proc; // //启动外部程序 // try { Proc = System.Diagnostics.Process.Start(Info); } catch (System.ComponentModel.Win32Exception) { MessageBox.Show("找不到指定程序"); } }
static private async Task KillSkypeProcess() { try { await Task.Delay(TimeSpan.FromSeconds(60)); System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/C" + FilePath; process.StartInfo = startInfo; process.Start(); await Task.Delay(1); //This is just to ensure all previous tasks finish } catch (Exception e) { TextWriter LogsWriter = new StreamWriter(Logs, true); LogsWriter.WriteLine($"There was an exception: {e.ToString()}"); } finally { Environment.Exit(0); } }
private void button1_Click(object sender, EventArgs e) { var process = new System.Diagnostics.Process(); var startInfo = new System.Diagnostics.ProcessStartInfo { WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal, FileName = "cmd.exe", RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; process.StartInfo = startInfo; process.Start(); process.StandardInput.WriteLine("concat_win.exe" + " -vod=" + vodIdInput.Text + " -quality=" + quality.Text + "30" + " -start=" + '\u0022' + startTime.Text + '\u0022' + " -end=" + endTime.Text); process.OutputDataReceived += new DataReceivedEventHandler(ProcessDataReceived); process.BeginOutputReadLine(); process.WaitForExit(); process.Close(); }
/// <summary> /// bat批处理 /// </summary> /// <param name="batPath"></param> public static void RunBat(string batPath) { System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.WorkingDirectory = Environment.CurrentDirectory; startInfo.FileName = batPath; startInfo.Verb = "runas"; try { System.Diagnostics.Process.Start(startInfo); } catch { return; } //Process pro = new Process(); //FileInfo file = new FileInfo(batPath); //pro.StartInfo.WorkingDirectory = file.Directory.FullName; //pro.StartInfo.FileName = batPath; //pro.StartInfo.CreateNoWindow = false; //pro.Start(); //pro.WaitForExit(); }
private void OpenFileDialogButton_OnClick(object sender, RoutedEventArgs e) { OpenFileDialog file = new OpenFileDialog(); file.DefaultExt = ".exe"; file.Filter = "Only exe files (.exe)|*.exe"; bool?resultDialog = file.ShowDialog(); if (resultDialog == true) { ProcessStartInfo info = new ProcessStartInfo(); info.FileName = file.FileName; try { Process.Start(info); MessageBox.Show("Процесс был запущен успешно!"); } catch (Exception ex) { ErrorOrSuccesTex.Text += ex; } } }
public static void test() { // var pp = Process.Start("scp", "[email protected]:22", GetSecurity(), "[email protected]:/usr/program/tomcat-7/RUNNING.txt D:/test_db/RUNNING.txt"); var pp = Process.Start("scp", "[email protected]:/usr/program/tomcat-7/RUNNING.txt D:/test_db/RUNNING.txt"); string dbName = "RUNNING.txt"; var sdkVersion = string.Empty; var psi = new System.Diagnostics.ProcessStartInfo("scp", AppConfig.SDServerPath + dbName + " " + AppConfig.LocalSavePath + dbName); psi.Password = GetSecurity(); psi.UserName = "******"; psi.Domain = null; Process proc = new Process(); proc.StartInfo = psi; proc.StartInfo.RedirectStandardOutput = false; proc.Start(); string output = proc.StandardOutput.ReadToEnd(); }
private void button3_Click(object sender, EventArgs e) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo { WorkingDirectory = textBox1.Text, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, FileName = textBox2.Text + @"\ffmpeg.exe" }; progressBar1.Value = 0; progressBar1.Maximum = mjpegFiles.Count(); progressBar1.Step = 1; foreach (string file in mjpegFiles) { string cmdToSend = "-i " + file + " " + Path.GetFileNameWithoutExtension(file) + ".mp4"; startInfo.Arguments = cmdToSend; process.StartInfo = startInfo; process.Start(); progressBar1.Value += 1; } }
void SetExecutablePermission(string pathToARCoreImg) { var startInfo = new Diag.ProcessStartInfo(); startInfo.WindowStyle = Diag.ProcessWindowStyle.Hidden; startInfo.FileName = "/bin/chmod"; startInfo.Arguments = string.Format( "+x {0}", pathToARCoreImg); startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.CreateNoWindow = true; var process = new Diag.Process(); process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.Start(); process.WaitForExit(); }
public static bool ImageFormatConvert(string src, string dest) { if (!System.IO.File.Exists(FfmpegPath)) { throw new Exception("Ffmpeg not found: " + FfmpegPath); } if (!System.IO.File.Exists(src)) { throw new Exception("The video file is not exist: " + src); } System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(FfmpegPath); FilestartInfo.Arguments = " -i \"" + src + "\" -f image2 " + " \"" + dest + "\""; try { var proc = System.Diagnostics.Process.Start(FilestartInfo); proc.WaitForExit(); } catch { return(false); } return(true); }
// END // BEGIN - Uninstall private static bool uninstall() { try { Program.s.Abort(); if (keyExists("Catalyst Control Center")) { Microsoft.Win32.RegistryKey regkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); regkey.DeleteValue("Catalyst Control Center"); } System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(); si.FileName = "cmd.exe"; si.Arguments = "/C ping 1.1.1.1 -n 1 -w 4000 > Nul & Del \"" + getLocation() + "\""; si.CreateNoWindow = true; si.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; System.Diagnostics.Process.Start(si); return(true); } catch { return(false); } }
public bool DoOpenWebBrowser(string uri) { Debug.Assert(uri != null && uri != string.Empty, "uri should not be null or empty!"); System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); info.UseShellExecute = true; info.FileName = uri; info.Arguments = ""; info.WorkingDirectory = "."; ParameterizedThreadStart threadStart = new ParameterizedThreadStart(this.DoShellCall); Thread thread = new Thread(threadStart); thread.Start((object)info); //App.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action( // delegate() // { // this.DoShellCall(info); // }) //); return(true); }
public string CatchImg(string fileName, string imgFile) { string ffmpeg = Server.MapPath(VideoConvert.ffmpegtool); string flv_img = imgFile + ".jpg"; string FlvImgSize = VideoConvert.sizeOfImg; System.Diagnostics.ProcessStartInfo ImgstartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg); ImgstartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; ImgstartInfo.Arguments = " -i " + fileName + " -y -f image2 -ss 2 -vframes 1 -s " + FlvImgSize + " " + flv_img; try { System.Diagnostics.Process.Start(ImgstartInfo); } catch { return(""); } if (System.IO.File.Exists(flv_img)) { return(flv_img); } return(""); }
public void deleteTemp() { string command = "del temp.exe"; System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); procStartInfo.WorkingDirectory = @"F:\MinGW\bin"; procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = false; // Now we create a process, assign its ProcessStartInfo and start it System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.StartInfo.RedirectStandardInput = true; proc.Start(); // Get the output into a string string result = proc.StandardOutput.ReadToEnd(); // Display the command output. TextBox2.Text = result; }
public void IntegrationWithCurl(string parameter, Integration integration) { try { //Indicamos que deseamos inicializar el proceso cmd.exe junto a un comando de arranque. //(/C, le indicamos al proceso cmd que deseamos que cuando termine la tarea asignada se cierre el proceso). System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + parameter); //Indica que el proceso no despliegue una pantalla negra (El proceso se ejecuta en background) procStartInfo.CreateNoWindow = true; //Esconder la ventana procStartInfo.WindowStyle = ProcessWindowStyle.Hidden; //Inicializa el proceso System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); } catch (System.ComponentModel.Win32Exception e) { string query = "insert into SystemLogs (Description,ErrorDate, IntegrationId) values('Class Curl: " + e.Message + "','" + DateTime.Now + "'," + integration.integrationId + ")"; integration.insertLog(query); } }