• 如何执行一条命令在C#里面。Process


    Introduction

    It is normal practice to open the Windows command prompt and execute commands. The command when executed shows the result onto the screen. There are many commands that we execute daily such as dir, find, etc. A situation may arise when you want to execute a (shell) command from the C# application.

    Don't worry!!! Here is the code to do so…

    Using the Code

    The code given below creates a process i.e. a command process and then invokes the command that we want to execute. The result of the command is stored in a string variable, which can then be used for further reference. The command execution can happen in two ways, synchronously and asynchronously. In the asynchronous command execution, we just invoke the command execution using a thread that runs independently. The code has enough comments, hence making it self-explanatory.

    Below is the code to execute the command synchronously:

    /// <span class="code-SummaryComment"><summary></span>
    /// Executes a shell command synchronously.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="command">string command</param></span>
    /// <span class="code-SummaryComment"><returns>string, as output of the command.</returns></span>
    public void ExecuteCommandSync(object command)
    {
         try
         {
             // create the ProcessStartInfo using "cmd" as the program to be run,
             // and "/c " as the parameters.
             // Incidentally, /c tells cmd that we want it to execute the command that follows,
             // and then exit.
        System.Diagnostics.ProcessStartInfo procStartInfo =
            new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
    
        // The following commands are needed to redirect the standard output.
        // This means that it will be redirected to the Process.StandardOutput StreamReader.
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        // Do not create the black window.
        procStartInfo.CreateNoWindow = true;
        // Now we create a process, assign its ProcessStartInfo and start it
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        // Get the output into a string
        string result = proc.StandardOutput.ReadToEnd();
        // Display the command output.
        Console.WriteLine(result);
          }
          catch (Exception objException)
          {
          // Log the exception
          }
    }

    The above code invokes the cmd process specifying the command to be executed. The optionprocStartInfo.RedirectStandardOutput is set to true, since we want the output to be redirected to theStreamReader. The procStartInfo.CreateNoWindow property is set to true, as we don't want the standard black window to appear. This will execute the command silently.

    Below is the code to execute the command asynchronously:

    /// <span class="code-SummaryComment"><summary></span>
    /// Execute the command Asynchronously.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="command">string command.</param></span>
    public void ExecuteCommandAsync(string command)
    {
       try
       {
        //Asynchronously start the Thread to process the Execute command request.
        Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
        //Make the thread as background thread.
        objThread.IsBackground = true;
        //Set the Priority of the thread.
        objThread.Priority = ThreadPriority.AboveNormal;
        //Start the thread.
        objThread.Start(command);
       }
       catch (ThreadStartException objException)
       {
        // Log the exception
       }
       catch (ThreadAbortException objException)
       {
        // Log the exception
       }
       catch (Exception objException)
       {
        // Log the exception
       }
    }

    If we observe carefully, the asynchronous execution of the command actually invokes the synchronous command execution method using a thread. The thread runs in the background making the command execution asynchronous in nature.

    In the above execution sample, we find that there are two result sets of the command "dir". The first one appears immediately after the command and the second appears after the "Done!" statement. In this case, the first one is the synchronous execution of the command, which happens immediately and the second is the asynchronous execution of the "dir" command.

    源地址:http://www.codeproject.com/Articles/25983/How-to-Execute-a-Command-in-C

  • 相关阅读:
    Leetcode Python笔记
    Jenkins 自动化构建基于svn的vue项目 ,以及uniapp的H5项目
    Jenkins 持续化部署
    java中的各种锁详细介绍
    Maven私有仓库搭建 Nexu3
    Spring Cloud构建微服务架构(一)服务注册与发现
    SpringCloud学习笔记(开篇)
    介绍一款 redis 可视化工具
    java 在线网络考试系统源码 springboot mybaits vue.js 前后分离跨域
    java OA办公系统源码 Springboot Activiti工作流 vue.js 前后分离 集成代码生成器
  • 原文地址:https://www.cnblogs.com/kissfu/p/3476911.html
Copyright © 2020-2023  润新知