c#运行外部文件

 
C#运行外部程序

使用方法:
System.Diagnostics.Process.Start("iexplore.exe", "http://hi.baidu.com/marsbook");

说明:
参数1为要运行的外部程序,参数2为所要运行程序的参数。

  这里所举的例子是用IE浏览器打开一个网址,而且是不会在IE的同一窗口打开页面,也就是每次都会用一个新的窗口打开这个链接所指向的页面。这个也可以用于LinkLabel控件实现WEB链接效果。


c#中的Process类可方便的调用外部程序,所以我们可以通过调用cmd.exe程序

加入参数 
"/c " + 要执行的命令来执行一个dos命令
/c代表执行参数指定的命令后关闭cmd.exe /k参数则不关闭cmd.exe)

    
private string RunCmd(string command)
         {
            
//實例一個Process類,啟動一個獨立進程
             Process p = new Process();

            
//Process類有一個StartInfo屬性,這個是ProcessStartInfo類,包括了一些屬性和方法,下面我們用到了他的幾個屬性:
 
           p.StartInfo.FileName 
= "cmd.exe";           //設定程序名
            p.StartInfo.Arguments = "/c " + command;    //設定程式執行參數
             p.StartInfo.UseShellExecute = false;        //關閉Shell的使用
            p.StartInfo.RedirectStandardInput = true;   //重定向標準輸入
             p.StartInfo.RedirectStandardOutput = true;  //重定向標準輸出
            p.StartInfo.RedirectStandardError = true;   //重定向錯誤輸出
             p.StartInfo.CreateNoWindow = true;          //設置不顯示窗口
 
             p.Start();   
//啟動
             
            
//p.StandardInput.WriteLine(command);       //也可以用這種方式輸入要執行的命令
             
//p.StandardInput.WriteLine("exit");        //不過要記得加上Exit要不然下一行程式執行的時候會當機
            
             
return p.StandardOutput.ReadToEnd();        //從輸出流取得命令執行結果
 
         }


public static void RunFile(string f)//打开一个外部文件
        {

            
//声明一个程序类
            System.Diagnostics.Process Proc; 
            
try
            {
                
//
                
//启动外部程序
                
//
                Proc = System.Diagnostics.Process.Start(f);
            }
            
catch (System.ComponentModel.Win32Exception)
            {
                
//Console.WriteLine("系统找不到指定的程序文件。\r{0}", e);
                return;
            }


        }
        
public static void RunIE(string command)//打开指定网页
        {
            Process myProcess 
= new Process();
            myProcess.StartInfo.FileName 
= "iexplore.exe";
            myProcess.StartInfo.Arguments 
= command;
            myProcess.Start();
            
return;       

        }
        
public static void RunOther(string name, string command)//打开其他程序
        {
            Process myProcess 
= new Process();

            myProcess.StartInfo.FileName 
= name;
            myProcess.StartInfo.Arguments 
= command;
            myProcess.Start();
            
return;

        }
posted on 2008-11-08 14:52  markbum  阅读(805)  评论(0)    收藏  举报