欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中隱式運(yùn)行CMD命令行窗口的方法

 更新時(shí)間:2011年04月30日 12:21:03   作者:  
下面介紹一種常用的在C#程序中調(diào)用CMD.exe程序,并且不顯示命令行窗口界面,來完成CMD中各種功能的簡(jiǎn)單方法。

MS的CMD命令行是一種重要的操作界面,一些在C#中不那么方便完成的功能,在CMD中幾個(gè)簡(jiǎn)單的命令或許就可以輕松搞定,如果能在C#中能完成CMD窗口的功能,那一定可以使我們的程序簡(jiǎn)便不少。
下面介紹一種常用的在C#程序中調(diào)用CMD.exe程序,并且不顯示命令行窗口界面,來完成CMD中各種功能的簡(jiǎn)單方法。
如下所示:

復(fù)制代碼 代碼如下:

System.Diagnosties.Process p=new System.Diagnosties.Process();
p.StartInfo.FileName="cmd.exe";//要執(zhí)行的程序名稱
p.StartInfo.UseShellExecute=false;
p.StartInfo.RedirectStanderInput=true;//可能接受來自調(diào)用程序的輸入信息
p.StartInfo.RedirectStanderOutput=true;//由調(diào)用程序獲取輸出信息
p.StartInfo.CreateNoWindow=true;//不顯示程序窗口
p.Start();//啟動(dòng)程序
//向CMD窗口發(fā)送輸入信息:
p.StanderInput.WriteLine("shutdown -r t 10"); //10秒后重啟(C#中可不好做哦)
//獲取CMD窗口的輸出信息:
string sOutput = p.StandardOutput.ReadToEnd();有啦以下代碼,就可以神不知鬼不覺的操作CMD啦??傊?,Process類是一個(gè)非常有用的類,它十分方便的利用第三方的程序擴(kuò)展了C#的功能。

詳細(xì)源碼如下:
復(fù)制代碼 代碼如下:

using System;
using System.Diagnostics;
namespace Business
{
/// <summary>
/// Command 的摘要說明。
/// </summary>
public class Command
{
private Process proc = null;
/// <summary>
/// 構(gòu)造方法
/// </summary>
public Command()
{
proc = new Process();
}
/// <summary>
/// 執(zhí)行CMD語句
/// </summary>
/// <param name="cmd">要執(zhí)行的CMD命令</param>
public void RunCmd(string cmd)
{
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.StandardInput.WriteLine(cmd);
proc.Close();
}
/// <summary>
/// 打開軟件并執(zhí)行命令
/// </summary>
/// <param name="programName">軟件路徑加名稱(.exe文件)</param>
/// <param name="cmd">要執(zhí)行的命令</param>
public void RunProgram(string programName,string cmd)
{
Process proc = new Process();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = programName;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
if (cmd.Length != 0)
{
proc.StandardInput.WriteLine(cmd);
}
proc.Close();
}
/// <summary>
/// 打開軟件
/// </summary>
/// <param name="programName">軟件路徑加名稱(.exe文件)</param>
public void RunProgram(string programName)
{
this.RunProgram(programName,"");
}
}
}

調(diào)用時(shí)
復(fù)制代碼 代碼如下:

Command cmd = new Command();
cmd.RunCmd("dir");

獲取輸出信息應(yīng)注意:

ReadtoEnd()容易卡?。?/P>

復(fù)制代碼 代碼如下:

[csharp] view plaincopyprint?string outStr = proc.StandardOutput.ReadtoEnd(); 

 string outStr = proc.StandardOutput.ReadtoEnd();


更傾向于使用ReadLine():

復(fù)制代碼 代碼如下:

[csharp] view plaincopyprint?string tmptStr = proc.StandardOutput.ReadLine(); 
         string outStr = ""; 
         while (tmptStr != "") 
         { 
             outStr += outStr; 
             tmptStr = proc.StandardOutput.ReadLine(); 
         } 

相關(guān)文章

最新評(píng)論