ASP.NET执行cmd命令

mac2022-06-30  26

 批处理命令,是执行速度最快效益最高的命令。因为批处理命令,说白了,就是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则表明了,在批处理命令之后自动换行。

转载于:https://www.cnblogs.com/LeeYZ/p/3403723.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)