本文主要是介绍在.Net中System.Diagnostics命名空间下Process类和ProcessStartInfo类的使用

用于启动一个外部程序所使用的类是Process,至于ProcessStartInfo类只是用来传入Process类所需要的参数,个人理解是有点类似于适配器的操作,不知道是否正确。

最简单的用于启动一个应用程序

  1. Process _proc = new Process();
  2.  
  3. ProcessStartInfo _procStartInfo = new ProcessStartInfo("IExplore.exe","http://www.baidu.com");
  4.  
  5. _proc.StartInfo = _procStartInfo;
  6.  
  7. _proc.Start();

以上就是简单的使用IE浏览器打开 百度首页 的代码,以上代码等价于

  1. Process _proc = new Process();
  2.  
  3. _proc.StartInfo.FileName = "IExplore.exe";
  4.  
  5. _proc.StartInfo.Arguments = "http://www.baidu.com";
  6.  
  7. _proc.Start();

可以通过直接给Process对象的属性赋值而达到相同的效果。

当需要执行一个脚本,比如执行windows系统下的.bat文件该怎么做

我们现在D盘目录下建立一个bat文件,写上内容

  1. xcopy /y C:\folder1\.txt C:\folder2\
  2.  
  3. ping localhost -n >nul
  4.  
  5. xcopy /y C:\folder1\.txt C:\folder2\
  6.  
  7. ping localhost -n >nul
  8.  
  9. xcopy /y C:\folder1\.txt C:\folder2\

脚本内容是把folder1的1.txt,2.txt,3.txt文件赋值到folder2下,在每个赋值命令的中间有ping命令,这是一个用于使一个脚本文件暂定一定时间的比较经典做法/y参数作用是当folder2文件夹下有同名的文件时,不提示而直接覆盖源文件,如果不加上这个参数当有同名的文件时会提示是否覆盖,此处暂停的时间为3秒,>nul 作用是只执行命令而不出现消息内容

  1. Process _proc = new Process();
  2.  
  3. ProcessStartInfo _procStartInfo = new ProcessStartInfo();
  4.  
  5. _procStartInfo.FileName = @"C:/Test.bat";
  6.  
  7. _procStartInfo.CreateNoWindow = true;
  8.  
  9. _procStartInfo.UseShellExecute = false;
  10.  
  11. _procStartInfo.RedirectStandardOutput = true;
  12.  
  13. _proc.StartInfo = _procStartInfo;
  14.  
  15. _proc.Start();
  16.  
  17. _proc.WaitForExit();
  18.  
  19. _proc.Kill();
  20.  
  21. using (StreamReader sr = _proc.StandardOutput) {
  22.  
  23. String str = sr.ReadLine();
  24.  
  25. while (null != str) {
  26.  
  27. Console.WriteLine(str);
  28.  
  29. str = sr.ReadLine();
  30.  
  31. }
  32.  
  33. }
  34.  
  35. if (_proc.HasExited)
  36.  
  37. _proc.Close();

此处提到三个属性:

CreateNoWindow:表示是否启动新的窗口来执行这个脚本,默认值为false,既不会开启新的窗口,当main线程运行完时,启动的控制台无法结束,需要等待脚本执行完毕才能继续,当手动设置为true,即脚本在后台新窗口执行(本人目前没有找到显示该新窗口的方法,如有悉者,敬请告知),main线程运行结束之后不必等待脚本执行完毕即可正常关闭,此时脚本在后台继续执行直至自动结束,往下看可以看到Process类的成员方法WaitForExit(int time)和Kill()方法,WaitForExit(int time)用于在time(毫秒)时间内等待脚本执行,当超过这个时间,main继续往下执行,脚本后台运行直至结束,如果不添加time参数,则无休止等待直至脚本运行完毕,Kill()方法用于停止该脚本的运行。由前面可以看出脚本总共需要至少6秒钟的时间,此时WaitForExit()参数设置为1000,则一秒之后,main函数不再等待脚本执行,此时查看folder2文件夹,发现复制了一个1.txt文件,然后运行kill()方法,脚本直接被终止,如果注释Kill()方法,则脚本会自动运行6秒之后自动停止。

UseShellExecute:是否使用外壳来运行程序,设置为true时运行程序会弹出新的cmd窗口执行脚本文件。当设置为false时则不使用外壳程序来运行。默认值为true

RedirectStandardOutput:获取对象的标准输出流StreamReader对象,用于输出脚本的返回内容,当该属性设置为true,则UseShellExecute属性必须设置为false,当加上外壳程序运行时,弹出新的窗口运行内容就是StandardOutput的读取内容。

除此之外还有RedirectStandardInput属性,可以用于默认人为输入命令。

运行完之后Process的HasExited属性可以判断脚本是否运行完毕。

ProcessStartInfo例子

如果你想在C#中以管理员新开一个进程,参考: Run process as administrator from a non-admin application

  1. ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\cmd.exe");
  2. info.UseShellExecute = true;
  3. info.Verb = "runas";
  4. Process.Start(info);

如果你想在命令行加参数,可以参考: Running CMD as administrator with an argument from C#

  1. Arguments = "/user:Administrator \"cmd /K " + command + "\""
  2.  
  3. -----------------------------------------------------------------------------------------
  4.  
  5. using System;
  6. using System.Diagnostics;
  7. using System.ComponentModel;
  8.  
  9. namespace MyProcessSample
  10. {
  11. /// <summary>
  12. /// Shell for the sample.
  13. /// </summary>
  14. class MyProcess
  15. {
  16. // These are the Win32 error code for file not found or access denied.
  17. const int ERROR_FILE_NOT_FOUND =;
  18. const int ERROR_ACCESS_DENIED = ;
  19.  
  20. /// <summary>
  21. /// Prints a file with a .doc extension.
  22. /// </summary>
  23. void PrintDoc()
  24. {
  25. Process myProcess = new Process();
  26.  
  27. try
  28. {
  29. // Get the path that stores user documents.
  30. string myDocumentsPath =
  31. Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  32.  
  33. myProcess.StartInfo.FileName = myDocumentsPath + "\\MyFile.doc";
  34. myProcess.StartInfo.Verb = "Print";
  35. myProcess.StartInfo.CreateNoWindow = true;
  36. myProcess.Start();
  37. }
  38. catch (Win32Exception e)
  39. {
  40. if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
  41. {
  42. Console.WriteLine(e.Message + ". Check the path.");
  43. }
  44.  
  45. else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
  46. {
  47. // Note that if your word processor might generate exceptions
  48. // such as this, which are handled first.
  49. Console.WriteLine(e.Message +
  50. ". You do not have permission to print this file.");
  51. }
  52. }
  53. }
  54.  
  55. public static void Main()
  56. {
  57. MyProcess myProcess = new MyProcess();
  58. myProcess.PrintDoc();
  59. }
  60. }
  61. }

(1) 打开文件

  1. private void btnopenfile_click(object sender, eventargs e)
  2. {
  3. // 定义一个 processstartinfo 实例
  4. processstartinfo psi = new processstartinfo();
  5. // 设置启动进程的初始目录
  6. psi.workingdirectory = application.startuppath;
  7. // 设置启动进程的应用程序或文档名
  8. psi.filename = @"xwy20110619.txt";
  9. // 设置启动进程的参数
  10. psi.arguments = "";
  11. //启动由包含进程启动信息的进程资源
  12. try
  13. {
  14. process.start(psi);
  15. }
  16. catch (system.componentmodel.win32exception ex)
  17. {
  18. messagebox.show(ex.message);
  19. return;
  20. }
  21. }

(2) 打开浏览器

  1. private void btnopenie_click(object sender, eventargs e)
  2. {
  3. // 启动ie进程
  4. process.start("iexplore.exe");
  5. }

(3)打开指定 url

  1. private void btnopenurl_click(object sender, eventargs e)
  2. {
  3. // 方法一
  4. // 启动带参数的ie进程
  5. process.start("iexplore.exe", "http://www.cnblogs.com/skysoot/");
  6.  
  7. // 方法二
  8. // 定义一个processstartinfo实例
  9. processstartinfo startinfo = new processstartinfo("iexplore.exe");
  10. // 设置进程参数
  11. startinfo.arguments = "http://www.cnblogs.com/skysoot/";
  12. // 并且使进程界面最小化
  13. startinfo.windowstyle = processwindowstyle.minimized;
  14. // 启动进程
  15. process.start(startinfo);
  16. }

(4) 打开文件夹

  1. private void btnopenfolder_click(object sender, eventargs e)
  2. {
  3. // 获取“收藏夹”文件路径
  4. string myfavoritespath = system.environment.getfolderpath(environment.specialfolder.favorites);
  5. // 启动进程
  6. system.diagnostics.process.start(myfavoritespath);
  7. }

(5) 打开文件夹

  1. private void btnprintdoc_click(object sender, eventargs e)
  2. {
  3. // 定义一个进程实例
  4. process myprocess = new process();
  5. try
  6. {
  7. // 设置进程的参数
  8. string mydocumentspath = environment.getfolderpath(environment.specialfolder.personal);
  9. myprocess.startinfo.filename = mydocumentspath + "\\txtfortest.txt";
  10. myprocess.startinfo.verb = "print";
  11.  
  12. // 显示txt文件的所有谓词: open,print,printto
  13. foreach (string v in myprocess.startinfo.verbs)
  14. {
  15. messagebox.show(v);
  16. }
  17.  
  18. // 是否在新窗口中启动该进程的值
  19. myprocess.startinfo.createnowindow = true;
  20. // 启动进程
  21. myprocess.start();
  22. }
  23. catch (win32exception ex)
  24. {
  25. if (ex.nativeerrorcode == )
  26. {
  27. messagebox.show(ex.message + " check the path." + myprocess.startinfo.filename);
  28. }
  29. else if (ex.nativeerrorcode == )
  30. {
  31. messagebox.show(ex.message + " you do not have permission to print this file.");
  32. }
  33. }

关于.Net中Process和ProcessStartInfor的使用的更多相关文章

  1. 利用.Net中Process类调用netstat命令来判断计算端口的使用情况

    利用.Net中Process类调用netstat命令来判断计算端口的使用情况: Process p = new Process();p.StartInfo = new ProcessStartInfo ...

  2. 关于.Net中Process的使用方法和各种用途汇总(一):Process用法简介

    简介: .Net中Process类功能十分强大.它可以接受程序路径启动程序,接受文件路径使用默认程序打开文件,接受超链接自动使用默认浏览器打开链接,或者打开指定文件夹等等功能. 想要使用Process ...

  3. C#中Process类的使用

    本文来自: http://www.cnblogs.com/kay/archive/2008/11/25/1340387.html Process 类的作用是对系统进程进行管理,我们使用Process类 ...

  4. node.js中process进程的概念和child_process子进程模块的使用

    进程,你可以把它理解成一个正在运行的程序.node.js中每个应用程序都是进程类的实例对象. node.js中有一个 process 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...

  5. Node.js中Process.nextTick()和setImmediate()的区别

    一.Webstrom使用node.js IDE的问题 在区别这两个函数之前来说一下Webstrom使用node.js IDE的问题,在配置Node.js的IDE了,但setImmediate().re ...

  6. C# ASP.NET中Process.Start没有反应也没有报错的解决方法

    最近有一个很坑的需求,在ASP.NET中打开一个access,还要用process.start打开,调试时一切正常,到了发布后就没有反应,找了一下午,各种设文件夹权限也不行,最后把应用程序池改成管理员 ...

  7. 关于.Net中Process的使用方法和各种用途汇总(二):用Process启动cmd.exe完成将cs编译成dll

    上一章博客我为大家介绍了Process类的所有基本使用方法,这一章博客我来为大家做一个小扩展,来熟悉一下Process类的实际使用,废话不多说我们开始演示. 先看看我们的软件要设计成的布局吧. 首先我 ...

  8. IIS7.0中Process打开cmd程序出现问题

    本人在VS中用Process打开cmd程序,并传入参数,转换图片,运行成功! 但是放入IIS7.0中,Process打不开cmd程序,程序直接运行过去,无结果,无报错! 解决方案: 将IIS里面你程序 ...

  9. NodeJs中process.cwd()与__dirname的区别

    process.cwd() 是当前执行node命令时候的文件夹地址 ——工作目录,保证了文件在不同的目录下执行时,路径始终不变__dirname 是被执行的js 文件的地址 ——文件所在目录 Node ...

随机推荐

  1. ./configure配置的参数 交叉编译 host,build target的含义

    交叉编译 host,build target的含义:build就是你正在使用的机器,host就是你编译好的程序可以运行的平台,target就是你编译的程序可以处理的平台.这个 build和host比较 ...

  2. 【Python】【demo实验25】【练习实例】

    原题: 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和. 我的源码: #!/usr/bin/python # encoding=utf-8 # -* ...

  3. 【3.3】mysql中的Federated存储引擎,远程表,相当于sql server的linked server

    MySQL中针对不同的功能需求提供了不同的存储引擎.所谓的存储引擎也就是MySQL下特定接口的具体实现. FEDERATED是其中一个专门针对远程数据库的实现.一般情况下在本地数据库中建表会在数据库目 ...

  4. *** 没有规则可以创建目标“test”。 停止。

    在编译Linux模块时出现这个问题,在仔细检查了Makefile没有错误后,重名了了该源程序和Makefile所在文件夹的名字,与源程序名字一致,然后问题就消失了!它们的关联体现在哪啊!?

  5. python基础知识0-4

    collection 他是对字典 元组 集合 进行加工的  是计数器 无论 深 ,浅 ,赋值 拷贝 内存地址都不变 赋值也是拷贝的一种 拷贝分两类数字 字符串 另一类: 列表 字典 元组 这一类还分两 ...

  6. Android MediaPlayer 在 STREAM_ALARM 中播放媒体

    最近因为公司需求,要实现后台播放音频,同时广告机中的视频因为客户需求调至静音,不能通过修改系统的媒体音量来让音频发声. private MediaPlayer mediaPlayer; private ...

  7. 【sublime Text】sublime Text3安装可以使xml格式化的插件

    应该有机会 ,会碰到需要格式化xml文件的情况. 例如,修改word转化的xml文件之后再将修改之后的xml文件转化为word文件. 但是,word另存的xml文件是没有格式的一片: 那怎么格式化 这 ...

  8. Android获取网络时间的方法

    一.通过免费或者收费的API接口获取 1.免费 QQ:http://cgi.im.qq.com/cgi-bin/cgi_svrtime 淘宝:http://api.m.taobao.com/rest/ ...

  9. .Net Core 3.0 内置依赖注入:举例

    原文:.Net Core 3.0 内置依赖注入:举例 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn ...

  10. asp.net 3.三层架构

    1.新建项目和类库 CZBK.ItcastProject (空白项目) CZBK.ItcastProject.BLL (类库) -- 逻辑业务 CZBK.ItcastProject.Common (类 ...