当前位置: 首页>>代码示例>>C#>>正文


C# Diagnostics.ProcessStartInfo类代码示例

本文整理汇总了C#中System.Diagnostics.ProcessStartInfo的典型用法代码示例。如果您正苦于以下问题:C# ProcessStartInfo类的具体用法?C# ProcessStartInfo怎么用?C# ProcessStartInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ProcessStartInfo类属于System.Diagnostics命名空间,在下文中一共展示了ProcessStartInfo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Button1Click

        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();
        }
开发者ID:eunsebi,项目名称:Cshap,代码行数:34,代码来源:MainForm.cs

示例2: Pack_Works

        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.");
            }
        }
开发者ID:ehvattum,项目名称:raven-csharp,代码行数:30,代码来源:NuGetTests.cs

示例3: WhenProcessTimesOut_TaskIsCanceled

            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);
            }
开发者ID:vector-man,项目名称:RunProcessAsTask,代码行数:35,代码来源:ProcessExTests.cs

示例4: CreateTestAndCoverageProcessStartInfo

        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;
        }
开发者ID:StefanN,项目名称:DojoTimer-for-.Net,代码行数:31,代码来源:ProcessStartInfoFactory.cs

示例5: Execute

 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);
 }
开发者ID:bielawb,项目名称:azure-sdk-tools,代码行数:7,代码来源:CsPack.cs

示例6: executeProcess

 /// <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);
     }
 }
开发者ID:phryneas,项目名称:eldo,代码行数:36,代码来源:Program.cs

示例7: CheckAdministrator

        /// <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);
            }
        }
开发者ID:AldarisX,项目名称:Sakuya-Aki,代码行数:34,代码来源:App.xaml.cs

示例8: SourceRevision

 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;
 }
开发者ID:WildGenie,项目名称:softlynx-activesql,代码行数:30,代码来源:Program.cs

示例9: RunAsync

        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;
        }
开发者ID:Refresh06,项目名称:visualmutator,代码行数:60,代码来源:Processes.cs

示例10: GetGitOnelineLogs

 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];
     }
 }
开发者ID:otf,项目名称:Mistilteinn,代码行数:25,代码来源:GitUtil.cs

示例11: Main

        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());

        }
开发者ID:seanjones,项目名称:Picasa-Wallpaper-Changer,代码行数:30,代码来源:Program.cs

示例12: AuthorizeServer

        /// <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();
            }
        }
开发者ID:kreeturez,项目名称:MediaBrowser,代码行数:42,代码来源:ServerAuthorization.cs

示例13: InvokeAndReturnOutput

        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;
            }
        }
开发者ID:Graham-Pedersen,项目名称:IronPlot,代码行数:34,代码来源:Program.cs

示例14: QueryFileDescriptor

        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;
        }
开发者ID:rLinks234,项目名称:nUtility,代码行数:33,代码来源:OSUtils.cs

示例15: runScript

        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;
        }
开发者ID:adzen,项目名称:NTNU-ITC-License,代码行数:26,代码来源:Form1.cs


注:本文中的System.Diagnostics.ProcessStartInfo类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。