C#程式調用外部程式

來源:互聯網
上載者:User

/*********************************************************

*  功        能:通過C#程式調用  Windows  記事本程式  編輯
*  名為  test.txt  的文字檔。
*
*  在整個程式中  System.Diagnostics.Process.Start(Info)  
*  為語句。
*  只是單獨執行一個外部程式,可用一條如下代碼即可:
*  System.Diagnostics.Process.Start(
*  "外部程式名","啟動參數");

*
*********************************************************/

 1 using  System;
2
3 class test
4 {
5 static void Main()
6 {
7
8 //聲明一個程式資訊類
9 System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
10
11 //設定外部程式名
12 Info.FileName = "notepad.exe";
13
14 //設定外部程式的啟動參數(命令列參數)為test.txt
15 Info.Arguments = "test.txt";
16
17 //設定外部程式工作目錄為 C:\
18 Info.WorkingDirectory = "C:\\";
19
20 //聲明一個程式類
21 System.Diagnostics.Process Proc ;
22
23 try
24 {
25 //
26 //啟動外部程式
27 //
28 Proc = System.Diagnostics.Process.Start(Info);
29 }
30 catch(System.ComponentModel.Win32Exception e)
31 {
32 Console.WriteLine("系統找不到指定的程式檔案。\r{0}", e);
33 return;
34 }
35
36 //列印出外部程式的開始執行時間
37 Console.WriteLine("外部程式的開始執行時間:{0}", Proc.StartTime);
38
39 //等待3秒鐘
40 Proc.WaitForExit(3000);
41
42 //如果這個外部程式沒有結束運行則對其強行終止
43 if(Proc.HasExited == false)
44 {
45 Console.WriteLine("由主程式強行終止外部程式的運行!");
46 Proc.Kill();
47 }
48 else
49 {
50 Console.WriteLine("由外部程式正常退出!");
51 }
52 Console.WriteLine("外部程式的結束已耗用時間:{0}", Proc.ExitTime);
53 Console.WriteLine("外部程式在結束運行時的傳回值:{0}", Proc.ExitCode);
54 }
55 }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.