关于.Net中Process和ProcessStartInfor的使用
本文主要是介绍在.Net中System.Diagnostics命名空间下Process类和ProcessStartInfo类的使用
用于启动一个外部程序所使用的类是Process,至于ProcessStartInfo类只是用来传入Process类所需要的参数,个人理解是有点类似于适配器的操作,不知道是否正确。
最简单的用于启动一个应用程序
Process _proc = new Process();
ProcessStartInfo _procStartInfo = new ProcessStartInfo("IExplore.exe","http://www.baidu.com");
_proc.StartInfo = _procStartInfo;
_proc.Start();
以上就是简单的使用IE浏览器打开 百度首页 的代码,以上代码等价于
Process _proc = new Process(); _proc.StartInfo.FileName = "IExplore.exe"; _proc.StartInfo.Arguments = "http://www.baidu.com"; _proc.Start();
可以通过直接给Process对象的属性赋值而达到相同的效果。
当需要执行一个脚本,比如执行windows系统下的.bat文件该怎么做
我们现在D盘目录下建立一个bat文件,写上内容
xcopy /y C:\folder1\.txt C:\folder2\ ping localhost -n >nul xcopy /y C:\folder1\.txt C:\folder2\ ping localhost -n >nul xcopy /y C:\folder1\.txt C:\folder2\
脚本内容是把folder1的1.txt,2.txt,3.txt文件赋值到folder2下,在每个赋值命令的中间有ping命令,这是一个用于使一个脚本文件暂定一定时间的比较经典做法/y参数作用是当folder2文件夹下有同名的文件时,不提示而直接覆盖源文件,如果不加上这个参数当有同名的文件时会提示是否覆盖,此处暂停的时间为3秒,>nul 作用是只执行命令而不出现消息内容
Process _proc = new Process();
ProcessStartInfo _procStartInfo = new ProcessStartInfo();
_procStartInfo.FileName = @"C:/Test.bat";
_procStartInfo.CreateNoWindow = true;
_procStartInfo.UseShellExecute = false;
_procStartInfo.RedirectStandardOutput = true;
_proc.StartInfo = _procStartInfo;
_proc.Start();
_proc.WaitForExit();
_proc.Kill();
using (StreamReader sr = _proc.StandardOutput) {
String str = sr.ReadLine();
while (null != str) {
Console.WriteLine(str);
str = sr.ReadLine();
}
}
if (_proc.HasExited)
_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
ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\cmd.exe");
info.UseShellExecute = true;
info.Verb = "runas";
Process.Start(info);
如果你想在命令行加参数,可以参考: Running CMD as administrator with an argument from C#
Arguments = "/user:Administrator \"cmd /K " + command + "\"" ----------------------------------------------------------------------------------------- using System;
using System.Diagnostics;
using System.ComponentModel; namespace MyProcessSample
{
/// <summary>
/// Shell for the sample.
/// </summary>
class MyProcess
{
// These are the Win32 error code for file not found or access denied.
const int ERROR_FILE_NOT_FOUND =;
const int ERROR_ACCESS_DENIED = ; /// <summary>
/// Prints a file with a .doc extension.
/// </summary>
void PrintDoc()
{
Process myProcess = new Process(); try
{
// Get the path that stores user documents.
string myDocumentsPath =
Environment.GetFolderPath(Environment.SpecialFolder.Personal); myProcess.StartInfo.FileName = myDocumentsPath + "\\MyFile.doc";
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
catch (Win32Exception e)
{
if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
{
Console.WriteLine(e.Message + ". Check the path.");
} else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
{
// Note that if your word processor might generate exceptions
// such as this, which are handled first.
Console.WriteLine(e.Message +
". You do not have permission to print this file.");
}
}
} public static void Main()
{
MyProcess myProcess = new MyProcess();
myProcess.PrintDoc();
}
}
}
(1) 打开文件
private void btnopenfile_click(object sender, eventargs e)
{
// 定义一个 processstartinfo 实例
processstartinfo psi = new processstartinfo();
// 设置启动进程的初始目录
psi.workingdirectory = application.startuppath;
// 设置启动进程的应用程序或文档名
psi.filename = @"xwy20110619.txt";
// 设置启动进程的参数
psi.arguments = "";
//启动由包含进程启动信息的进程资源
try
{
process.start(psi);
}
catch (system.componentmodel.win32exception ex)
{
messagebox.show(ex.message);
return;
}
}
(2) 打开浏览器
private void btnopenie_click(object sender, eventargs e)
{
// 启动ie进程
process.start("iexplore.exe");
}
(3)打开指定 url
private void btnopenurl_click(object sender, eventargs e)
{
// 方法一
// 启动带参数的ie进程
process.start("iexplore.exe", "http://www.cnblogs.com/skysoot/"); // 方法二
// 定义一个processstartinfo实例
processstartinfo startinfo = new processstartinfo("iexplore.exe");
// 设置进程参数
startinfo.arguments = "http://www.cnblogs.com/skysoot/";
// 并且使进程界面最小化
startinfo.windowstyle = processwindowstyle.minimized;
// 启动进程
process.start(startinfo);
}
(4) 打开文件夹
private void btnopenfolder_click(object sender, eventargs e)
{
// 获取“收藏夹”文件路径
string myfavoritespath = system.environment.getfolderpath(environment.specialfolder.favorites);
// 启动进程
system.diagnostics.process.start(myfavoritespath);
}
(5) 打开文件夹
private void btnprintdoc_click(object sender, eventargs e)
{
// 定义一个进程实例
process myprocess = new process();
try
{
// 设置进程的参数
string mydocumentspath = environment.getfolderpath(environment.specialfolder.personal);
myprocess.startinfo.filename = mydocumentspath + "\\txtfortest.txt";
myprocess.startinfo.verb = "print"; // 显示txt文件的所有谓词: open,print,printto
foreach (string v in myprocess.startinfo.verbs)
{
messagebox.show(v);
} // 是否在新窗口中启动该进程的值
myprocess.startinfo.createnowindow = true;
// 启动进程
myprocess.start();
}
catch (win32exception ex)
{
if (ex.nativeerrorcode == )
{
messagebox.show(ex.message + " check the path." + myprocess.startinfo.filename);
}
else if (ex.nativeerrorcode == )
{
messagebox.show(ex.message + " you do not have permission to print this file.");
}
}
关于.Net中Process和ProcessStartInfor的使用的更多相关文章
- 利用.Net中Process类调用netstat命令来判断计算端口的使用情况
利用.Net中Process类调用netstat命令来判断计算端口的使用情况: Process p = new Process();p.StartInfo = new ProcessStartInfo ...
- 关于.Net中Process的使用方法和各种用途汇总(一):Process用法简介
简介: .Net中Process类功能十分强大.它可以接受程序路径启动程序,接受文件路径使用默认程序打开文件,接受超链接自动使用默认浏览器打开链接,或者打开指定文件夹等等功能. 想要使用Process ...
- C#中Process类的使用
本文来自: http://www.cnblogs.com/kay/archive/2008/11/25/1340387.html Process 类的作用是对系统进程进行管理,我们使用Process类 ...
- node.js中process进程的概念和child_process子进程模块的使用
进程,你可以把它理解成一个正在运行的程序.node.js中每个应用程序都是进程类的实例对象. node.js中有一个 process 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...
- Node.js中Process.nextTick()和setImmediate()的区别
一.Webstrom使用node.js IDE的问题 在区别这两个函数之前来说一下Webstrom使用node.js IDE的问题,在配置Node.js的IDE了,但setImmediate().re ...
- C# ASP.NET中Process.Start没有反应也没有报错的解决方法
最近有一个很坑的需求,在ASP.NET中打开一个access,还要用process.start打开,调试时一切正常,到了发布后就没有反应,找了一下午,各种设文件夹权限也不行,最后把应用程序池改成管理员 ...
- 关于.Net中Process的使用方法和各种用途汇总(二):用Process启动cmd.exe完成将cs编译成dll
上一章博客我为大家介绍了Process类的所有基本使用方法,这一章博客我来为大家做一个小扩展,来熟悉一下Process类的实际使用,废话不多说我们开始演示. 先看看我们的软件要设计成的布局吧. 首先我 ...
- IIS7.0中Process打开cmd程序出现问题
本人在VS中用Process打开cmd程序,并传入参数,转换图片,运行成功! 但是放入IIS7.0中,Process打不开cmd程序,程序直接运行过去,无结果,无报错! 解决方案: 将IIS里面你程序 ...
- NodeJs中process.cwd()与__dirname的区别
process.cwd() 是当前执行node命令时候的文件夹地址 ——工作目录,保证了文件在不同的目录下执行时,路径始终不变__dirname 是被执行的js 文件的地址 ——文件所在目录 Node ...
随机推荐
- 【LOJ】#3046. 「ZJOI2019」语言
LOJ#3046. 「ZJOI2019」语言 先orz zsy吧 有一个\(n\log^3n\)的做法是把树链剖分后,形成logn个区间,这些区间两两搭配可以获得一个矩形,求矩形面积并 然后就是对于一 ...
- Android Application的基本组件介绍
一个Android应用通常由一个或多个基本组件组成,常用的一般有Activity.Service.BroadcastReceiver.ContentProvider.Intent等等. ⒈Activi ...
- php+lottery.js制作九宫格抽奖实例
php+lottery.js制作九宫格抽奖实例,本抽奖功能效果表现好,定制方便简单,新手学习跟直接拿来用都非常不错,兼容IE.火狐.谷歌等浏览器. 引入抽奖插件lottery.js <scrip ...
- PHP中addslashes()和htmlspecialchars() 函数的区别及应用
addslashes()防sql注入: 定义如下: addslashes() 函数返回在预定义字符之前添加反斜杠的字符串. 预定义字符是: 单引号(') 双引号(") 反斜杠(\) NULL ...
- 怎样解决在执行 vue init 时提示 "vue : 无法加载文件" 的问题?
注意, 以下操作需要 以管理员身份 在 PowerShell 中进行, 不能是 CMD / Git Bash 等. 1. 以 管理员身份 运行 PowerShell 2. 执行 get-Executi ...
- .Net Core 3.0 内置依赖注入:举例
原文:.Net Core 3.0 内置依赖注入:举例 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn ...
- work mark
<detection name="tracking" open="1" shape="rect" rect="(608,16 ...
- hbase shell 基本操作
hbase shell 基本操作 启动HBASE [hadoop@master ~]$hbase shell 2019-01-24 13:53:59,990 WARN [main] ut ...
- Linux 永久挂载镜像文件和制作yum源
Linux mount命令是经常会使用到的命令,它用于挂载Linux系统外的文件. 1.镜像挂载到系统指定目录下:[root@master cdrom]# mount -t auto /mnt/c ...
- centos 7 firewall(防火墙)开放端口/删除端口/查看端口
1.firewall的基本启动/停止/重启命令 复制#centos7启动防火墙 systemctl start firewalld.service #centos7停止防火墙/关闭防火墙 system ...