读书人

C# Process 种的思考

发布时间: 2012-12-20 09:53:21 作者: rapoo

C# Process 类的思考

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

下面我们用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();

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

?

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

?

?现在 在写一个读入文件的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();        }

?

读书人网 >C#

热点推荐