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:

 Collapse | Copy Code
/// <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:

 Collapse | Copy Code
/// <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

如何执行一条命令在C#里面。Process的更多相关文章

  1. linux系统执行多条命令,linux系统执行复合命令

    在操作linux系统的时候,你是否遇到过打开一个目录,然后查看一个文件里面的内容. 我们可以使用命令   cd + 目录     cat + 文件名,我们需要输入两次,点击两次 enter   有没有 ...

  2. Linux重复执行上条命令

    Linux系统下Shell重复执行上条命令的 4 种方法: 1.使用上方向键,并回车执行.2.按 !! 并回车执行.3.输入 !-1 并回车执行.4.按 Ctrl+P 并回车执行.

  3. Linux下间隔多少秒 (即以秒为单位) 去执行某条命令或某个shell脚本的操作方法【转】

    在日常运维工作中, 经常会碰到以秒为单位去定时执行某些命令或监控脚本的需求. 说到定时任务就要用到crontab,通常来说,crontab的最小单位是分钟级别,要想实现秒级别的定时任务,就要进行特殊设 ...

  4. PowerShell一次执行多条命令

    PowerShell一次执行多条命令语句 使用CMD之后换到PS之后想一次执行多条命令会很不习惯,因为原来的&&语句连接符已经不能用了. 在各种搜索后没有发现网上有说明这个的.无奈只能 ...

  5. supervisor的command执行两条命令

    如下supervisor的进程的comand配置参数只能写一个命令 1.要执行多条命令,可以写个sh文件包含多条命令,然后sh -x   xxxx.sh,但这样又多了一个文件, 2.把所有命令放在字符 ...

  6. linux sheel重复执行上条命令

    Linux系统下Shell重复执行上条命令的 4 种方法: 1.使用上方向键,并回车执行. 2.按 !! 并回车执行. 3.输入 !-1 并回车执行. 4.按 Ctrl+P 并回车执行.

  7. ssh 执行多条命令包含awk的用法

    格式:ssh user@ip command 单条命令:ssh user@ip command1 多条命令:ssh user@ip "command1;command2" 不加双引 ...

  8. [教程]K8Cscan调用外部程序(Win/Linux批量上控/执行多条命令/保存结果)

    0x000 调用原理 Cscan调用外部程序有两种方式,一是编写DLL,二是配置文件 编写DLL文件对于不懂编程的人来说可能会很难(虽然支持各语言) 由于考虑到很多人不会编程或会编程又急用无法短时间转 ...

  9. 【转】使用shell登录远程服务器执行多条命令,ssh登录之后执行脚本文件

    原文:https://blog.csdn.net/qq_36622490/article/details/100773589 这个需求主要是我在jenkins中pipeline的代码里,需要使用she ...

  10. Linux连续执行多条命令

    引自:这里 每条命令使用";"隔开,则无论前边的命令执行成功与否都会继续执行下一条命令这里,故意将第二条命令中的echo多写了一个o,命令执行出错,但并不影响后续命令的执行可以这么 ...

随机推荐

  1. 写个屏蔽百度搜索广告的Chrome插件

    工作生活都用百度比较多,毕竟它是目前为止感觉最好的国内PC搜索引擎.我纵使已经差不多炼成了一眼过滤广告的眼力,但始终觉得碍眼,感觉还是写个插件把它屏蔽了吧.这个插件开发的门槛其实非常低,只是一开始做不 ...

  2. leetcode 315. Count of Smaller Numbers After Self 两种思路(欢迎探讨更优解法)

    说来惭愧,已经四个月没有切 leetcode 上的题目了. 虽然工作中很少(几乎)没有用到什么高级算法,数据结构,但是我一直坚信 "任何语言都会过时,只有数据结构和算法才能永恒". ...

  3. 2016 5.03开始记录我的it学习。

    好多谢立成师兄给我这个网址,我发现博客园不仅仅可以随笔记载很多东西,还是一个资源丰富的网站,接下来的四年我会用心去记录这些学习的点滴.

  4. ERROR: “System.Web.Mvc.Controller.File(string, string, string)”是一个“方法”

    ERROR: “System.Web.Mvc.Controller.File(string, string, string)”是一个“方法”,这在给定的上下文中无效 这是一个与Controller.F ...

  5. JPA和hibernate的关系

    实际上,JPA的标准的定制是hibernate作者参与定制的,所以JPA是hibernate的一个总成,可以这么理解

  6. 为什么要加入<!doctype html>这个文档声明——IE怪异模式

    调试了很久,发现了一个非常细微但又十分重要的问题,又一次我在对于文档声明类型的时候,声明了如下类型 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1 ...

  7. linux基础-第十七单元 Samba服务

    Samba的功能 Samba的安装 Samba服务的启动.停止.重启 Samba服务的配置 Samba服务的主配置文件 samba服务器配置实例 Samba客户端设置 windows客户端 Linux ...

  8. linux基础-第六单元 用户、群组和权限

    用户及passwd文件 /etc/passwd文件的功能 /etc/passwd文件每个字段的具体含义 shadow文件 /etc/shadow文件的功能 /etc/shadow文件每个字段的具体含义 ...

  9. 链队列的C/C++实现

    #include <iostream> using namespace std; const int N = 10; typedef int ELEMTYPE; typedef struc ...

  10. 单例模式(Singleton Pattern)

    意图 保证一个类仅有一个实例,并提供一个该实例的全局访问点 可将一个实例扩展到n个实例.限定某类最多只能创建n个实例. 双重锁定实现单例模式 C# public sealed class Single ...