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. 产品列表页分类筛选、排序的算法实现(PHP)

    一.简单的单条件查询 工作都是从简单的开始,先从最简单的单表查询开始,这个一般用在首页以及一些比较独立的页面,只需要查找几个符合条件的产品展示出来即可,可以使用分页或者不使用分页.下面这个是产品控制器 ...

  2. unity3d 三分钟实现简单的赛车漂移

    提到赛车游戏,大家最关心的应该就是漂移吧?! 从学unity开始,我就一直在断断续续的研究赛车 因为自己技术太烂.悟性太差等原因,我走了不少弯路 也许你会说,网上那么多资料,你不会查啊 是啊!网上一搜 ...

  3. dnsunlocker解决

    环境:windows 10 中文企业版,firefox47, chrome51 安装了某个国外程序后,浏览器各种不正常,打开网页慢,或是无法打开,更严重的是会弹广告,各种广告. 然后在控制面板中卸载了 ...

  4. NPOI2.0学习(一)

    引用空间 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; 创建工作簿(workbook)和sheet HSSFWorkbook wk = new ...

  5. 服务链(Service Chaining,or Service Function Chaining,SFC,功能服务链)

    Software-configured  service  chaining  provides  the  capability  to  dynamically include best-of-b ...

  6. Beta--项目冲刺第七天

    胜利在望-- 队伍:F4 成员:031302301 毕容甲 031302302 蔡逸轩 031302430 肖阳 031302418 黄彦宁 会议内容: 1.站立式会议照片: 2.项目燃尽图 3.冲刺 ...

  7. extjs 箱子布局

    a.flex 配置项 flex 配置项不是设置在布局上,而是设置在子项的配置项.每个子项相对的 flex 值都会与全体子项 flex 累加的值相比较,根据此结果,处理每个子项的 flex 最后是多少. ...

  8. Android Toast效果设置

    Android Toast效果设置 Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失.总 ...

  9. python+urllib+beautifulSoup实现一个简单的爬虫

    urllib是python3.x中提供的一系列操作的URL的库,它可以轻松的模拟用户使用浏览器访问网页. Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能 ...

  10. 【BZOJ 4456】【UOJ #184】【ZJOI 2016】旅行者

    http://www.lydsy.com/JudgeOnline/problem.php?id=4456 http://uoj.ac/problem/184 参考(抄)的晨爷的题解(代码) 对矩形进行 ...