最近写了两个小程序都要调用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#