批處理命令,是執行速度最快效益最高的命令。因為批處理命令,說白了,就是ms-dos環境下的命令,有很多的批處理命令,都是純DOS下的命令。
然而,批處理命令盡管功能強大,卻存在不足之處。批處理命令只能完成基礎性的功能,無法完成復雜的網絡功能。因此,在很多情況下,程序開發者通常會使用各種開發語言作為開發工具,配合着批處理命令,實現功能強大執行速度較快的項目。
下面,本站給大家介紹的是,如何在CS結構的C#程序中,調用ms-dos窗口,運行多條批處理命令。
一、引入命名空間
首先在CS文件頭中,引用如下的代碼:
using System.Diagnostics;
二、函數代碼
public void MyBatCommand()//名稱
{
//如下的三個字符串,代表三條批處理命令
string MyDosComLine1, MyDosComLine2, MyDosComLine3;
MyDosComLine1 = "cd\";//返回根目錄命令
MyDosComLine2 = "cd MyFiles";//進入MyFiles目錄
MyDosComLine3 = "copy *.* e:\";//將當前目錄所有文件復制粘貼到E盤
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe ";//打開DOS控制平台
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = true;//是否顯示DOS窗口,true代表隱藏;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardError = true;
myProcess.Start();
StreamWriter sIn = myProcess.StandardInput;//標准輸入流
sIn.AutoFlush = true;
StreamReader sOut = myProcess.StandardOutput;//標准輸入流
StreamReader sErr = myProcess.StandardError;//標准錯誤流
sIn.Write(MyDosComLine1 System.Environment.NewLine);//第一條DOS命令
sIn.Write(MyDosComLine2 System.Environment.NewLine);//第二條DOS命令
sIn.Write(MyDosComLine3 System.Environment.NewLine);//第三條DOS命令
sIn.Write("exit" System.Environment.NewLine);//第四條DOS命令,退出DOS窗口
string s = sOut.ReadToEnd();//讀取執行DOS命令后輸出信息
string er = sErr.ReadToEnd();//讀取執行DOS命令后錯誤信息
if (myProcess.HasExited == false)
{
myProcess.Kill();
//MessageBox.Show(er);
}
else
{
//MessageBox.Show(s);
}
sIn.Close();
sOut.Close();
sErr.Close();
myProcess.Close();
}
部分代碼解釋:
想通過c#運行多條批處理命令,我們可以使用如下的格式來添加多條命令。
sIn.Write(DOS命令代碼 System.Environment.NewLine);
其中,DOS命令代碼就是您想執行批處理命令,而System.Environment.NewLine則表明了,在批處理命令之后自動換行。