星空网 > 软件开发 > 操作系统

C#调用CMD程序

最近写了两个小程序都要调用Windows自带的命令行程序,一个是调用Openfiles.exe查询正在编辑的共享文档,一个是调用DiskPart.exe查询硬盘状态。两种命令行程序调用有点不同,记录一下。

1.用ProcessStartInfo配置参数调用。

这种是在CMD里直接带参数输入的,要注意的是要处理错误输出,可能同时有错误和标准输出的。

      ProcessStartInfo start = new ProcessStartInfo("openfiles");//设置运行的命令行程序,不在系统环境变量的要输入完整路径      start.Arguments = "/Query /V /NH /S " + host + " /U " + user + " /P " + passWord;  //命令行程序的参数      start.CreateNoWindow = true;//不显示dos命令行窗口      start.RedirectStandardOutput = true;//标准输出      start.RedirectStandardInput = true;//标准输入      start.RedirectStandardError = true;//错误输出      start.UseShellExecute = false;// //指定不使用系统的外壳程序,而是直接启动被调用程序本身      Process p = Process.Start(start);      StreamReader reader = p.StandardOutput;//截取输出流      errorMSG = p.StandardError.ReadLine(); //读取错误输出            string result = reader.ReadToEnd();  //读取标准输出      p.WaitForExit();  //等待程序执行完退出进程      p.Close();  //关闭进程      reader.Close();  //关闭流    

 

2.用Process..StandardInput.WriteLine方法输入的。

这类通常可以直接双击打开运行等待输入。要注意需要输入exit退出后才读取到输出的。这种也可以将输入先写在单独的文件然后将文件作为参数输入,除非经常要修改作测试不然写参数在文件有乜好?

      Process p = new Process();                  // new instance of Process class      p.StartInfo.UseShellExecute = false;             // do not start a new shell      p.StartInfo.RedirectStandardOutput = true;          // Redirects the on screen results      p.StartInfo.FileName = "diskpart.exe";            // executable to run      p.StartInfo.RedirectStandardInput = true;           // Redirects the input commands      p.Start();                          // Starts the process      p.StandardInput.WriteLine("List volume");           // Issues commands to diskpart      p.StandardInput.WriteLine("exit");      //要上面Exit了才能读取      StreamReader reader = p.StandardOutput;//截取输出流      string output = null;//每次读取一行      while (!reader.EndOfStream)      {          output += Environment.NewLine;      }      p.WaitForExit();  // Waits for the exe to finish      p.Close();     //关闭进程      reader.Close();   //关闭流 

 

参考:
Using DiskPart with C#
https://ndswanson.wordpress.com/2014/08/12/using-diskpart-with-c/

 




原标题:C#调用CMD程序

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

广州新加坡专线:https://www.goluckyvip.com/tag/32214.html
shopify老:https://www.goluckyvip.com/tag/3222.html
广州印度专线:https://www.goluckyvip.com/tag/32223.html
广州至澳门物流:https://www.goluckyvip.com/tag/32228.html
广州至澳门专线:https://www.goluckyvip.com/tag/32229.html
FBM测款:https://www.goluckyvip.com/tag/3223.html
在古巴做游轮 古巴旅游项目:https://www.vstour.cn/a/363194.html
西藏旅游攻略自驾游需要多少天 去西藏旅游自驾游要多久时间:https://www.vstour.cn/a/363195.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流