zoukankan      html  css  js  c++  java
  • 关于.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:folder11.txt C:folder2
    
    ping localhost -n 3 >nul
    
    xcopy /y C:folder12.txt C:folder2
    
    ping localhost -n 3 >nul
    
    xcopy /y C:folder13.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(1000);
    
    _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:Windowscmd.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 =2;
            const int ERROR_ACCESS_DENIED = 5;
    
            /// <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 == 1)
                    {
                        messagebox.show(ex.message + " check the path." + myprocess.startinfo.filename);
                    }
                    else if (ex.nativeerrorcode == 2)
                    {
                        messagebox.show(ex.message + " you do not have permission to print this file.");
                    }
                }
    萌橙 你瞅啥?
  • 相关阅读:
    Deploying a web application to Jetty
    在java语言中执行jruby
    自制chuncked http streaming 流
    ubuntu11.10 rails开发集成vim相关问题
    通过drb集成java和ruby环境
    使用Java Web Start部署JRuby应用
    JRuby使用经验 Ruby language ITeye论坛
    使用Trinidad當Jruby Server.
    高雄 linux usergroup
    Jruby On Rails 的安装及部署实践
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/11854889.html
Copyright © 2011-2022 走看看