本文主要是介紹在.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\1.txt C:\folder2\ ping localhost -n 3 >nul xcopy /y C:\folder1\2.txt C:\folder2\ ping localhost -n 3 >nul xcopy /y C:\folder1\3.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:\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 =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."); } }