C#Process类的思考

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

在这里,我先给自己留个印象

下面我们用C#实现一个调用Dos命令的小程序,让大家对系统进程能有个直观的了解.要使用PRocess类,首先要引入System.Diagnostic命名空间,然后定义一个新的Process类,将其制定为打开一个Cmd.exe的命令,然后根据其的StanderInput和StanderOutput对其进行命令的输入和信息的读出.具体程序如下:

Process p=new Process();

p.StartInfo.FileName="cmd.exe"; //设置启动的进程命令

/**设置是否标准输入输出和标准错误,当这些都设为true时

**UseShellExcute必须为 false*/

p.StartInfo.UseShellExcute=false;

p.StartInfo.RedirectStanderInput=true;

p.StartInfo.RedirectStanderOutput=true;

p.StartInfo.RedirectStanderError=true;

p.StartInfo.CreatNoWindows=true;

p.start();

//向Dos窗口中输入ping的命令,这里的ip值请自己设置

p.StandardInput.WriteLine("ping -n 1 "+IP);

//输入退出窗口的命令

p..StandardInput.WriteLine("Exit");

/**这里用ReadToEnd读出输出并将其赋给一个string值,这里要

**注意的是ReadToEnd这个命令是在调用的程序结束后才可以执行的,所以

**要是把这句放在上面的"Exit"之后,程序就会进入一个死循环*/

string output= p.StandardOutput.ReadToEnd();

主要的工作已经完成了,下来就看你怎样利用程序的输入输出来完成一些功能了.

在这里我也写了一个实现:

Program代码

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace Consoleapplication1 { class Program { static void Main(string[] args) { Process process = new Process(); string strBatPath = "E:/test.bat"; string mess = ExecuteBAT(strBatPath, process); Console.WriteLine(mess); Console.ReadKey(); } private static string ExecuteBAT(string strBatPath, Process pro) //文件路径;要执行bat文件的进程,返回执行结果 { string mess = ""; try { pro.StartInfo.UseShellExecute = true; //strBatPath是bat文件路径 pro.StartInfo.FileName = strBatPath; pro.StartInfo.CreateNoWindow = true; if (pro.Start()) { //写日志文件 mess = DateTime.Now.ToLongDateString() + " " + strBatPath + "执行成功"; } else { mess = string.Format("执行{0}失败.", strBatPath); } } catch (Exception ex) { mess = ex.Message; } finally { pro.Close(); } return mess; } } }

现在 在写一个读入文件的C#方法

C#代码

public static void printFile(string strFileName) { StreamReader srd; try { srd = File.OpenText(strFileName); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("File not read"); return; } while(srd.Peek()!=-1) { string str = srd.ReadLine(); Console.WriteLine(str); } Console.WriteLine("End of read"); srd.Close(); } public static void InputFile(string strFileName) { StreamWriter swt; try { swt = File.CreateText(strFileName); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("File not Write"); return; } swt.WriteLine("chenhailong"); swt.Close(); }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航