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. DOM与元素节点内联样式

    获取.设置及移除单个内联 CSS 属性 每个 HTML 元素都有个 style 属性,可以用来插入针对该元素的内联 CSS 属性. <div style='background-color:bl ...

  2. Javascript中的循环变量声明,到底应该放在哪儿?

    相信很多Javascript开发者都在声明循环变量时犹豫过var i到底应该放在哪里:放在不同的位置会对程序的运行产生怎样的影响?哪一种方式符合Javascript的语言规范?哪一种方式和ecma标准 ...

  3. Button、ImageButton及ImageView详解

    Button.ImageButton及ImageView详解 在应用程序开发过程中,很多时候需要将View的background或者src属性设置为图片,即美观又支持点击等操作.常见的有Button. ...

  4. 代码生成工具——CodeSmith

    1.绿色版软件下载:http://download.csdn.net/detail/laoge/6859701 2.破解说明:http://tieba.baidu.com/p/3373160396 3 ...

  5. Ubuntu's Trash

    1.Location    Where is Trash?    /home/userName/.local/share/Trash2.Under Trash    Three files:      ...

  6. 让所有的浏览器都支持html5

    <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" ...

  7. 使用Git时一些问题的处理

    更新日志: 2016.06.04 晚 添加 git push --force (用于删除高版本的commit) 2015.11.29 晚 添加冲突处理工具Meld的教程 添加在GitHub上Rever ...

  8. Android 用代码设置Shape,corners,Gradient

    网上查找资料 记录学习 int strokeWidth = 5; // 3dp 边框宽度 int roundRadius = 15; // 8dp 圆角半径 int strokeColor = Col ...

  9. 概率DP light oj 1038

    t个数据 然后一个n 输出变成1的期望 看个数据 dp[n]代表n变成1的期望 cnt代表因子个数 pi代表因子 那么dp[n]=1/cnt*(dp[n/p1]+1)+1/cnt*(dp[n/p2]+ ...

  10. 安装python-docx

    安装环境: windows 7 64位 python 3.4.2 64位 说明: 用pip install python-docx不行,当装lxml时出现错误,一直卡在那. 安装非官方的版本,如下图, ...