C#中子進(jìn)程的啟動(dòng)參數(shù)設(shè)置

c#
小樊
83
2024-08-27 10:03:10

在C#中,你可以使用System.Diagnostics.Process類(lèi)來(lái)啟動(dòng)子進(jìn)程并設(shè)置其啟動(dòng)參數(shù)

using System;
using System.Diagnostics;

namespace SubprocessExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創(chuàng)建一個(gè)新的ProcessStartInfo對(duì)象
            ProcessStartInfo startInfo = new ProcessStartInfo();
            
            // 設(shè)置子進(jìn)程的可執(zhí)行文件路徑
            startInfo.FileName = "your_executable_file.exe";
            
            // 設(shè)置子進(jìn)程的啟動(dòng)參數(shù)
            startInfo.Arguments = "arg1 arg2 arg3";
            
            // 如果需要,可以設(shè)置其他屬性,例如工作目錄、窗口樣式等
            startInfo.WorkingDirectory = "path_to_working_directory";
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            
            // 使用ProcessStartInfo對(duì)象啟動(dòng)子進(jìn)程
            Process process = Process.Start(startInfo);
            
            // 等待子進(jìn)程退出
            process.WaitForExit();
            
            // 獲取子進(jìn)程的退出代碼
            int exitCode = process.ExitCode;
            Console.WriteLine($"Subprocess exited with code: {exitCode}");
        }
    }
}

在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)ProcessStartInfo對(duì)象,然后設(shè)置了子進(jìn)程的可執(zhí)行文件路徑和啟動(dòng)參數(shù)。接下來(lái),我們使用Process.Start()方法啟動(dòng)子進(jìn)程,并等待其退出。最后,我們獲取子進(jìn)程的退出代碼并將其輸出到控制臺(tái)。

0