Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách chạy ứng dụng bên ngoài từ ứng dụng C#

Một ứng dụng bên ngoài có thể được chạy từ ứng dụng C# sử dụng Process. Process là chương trình đang chạy trên máy tính của bạn. Điều này có thể là từ một background task nhỏ như spell-checker hay system events handler đến một ứng dụng đầy đủ như Notepad, v.v.

Mỗi process cung cấp tài nguyên cần thiết để thực thi một chương trình. Mỗi process được bắt đầu với một thread đơn lẻ, gọi là primary thread. Một process có thể có nhiều thread ngoài primary thread. Process phụ thuộc nhiều vào system resources trong khi thread yêu cầu tối thiểu resources, nên process được coi là heavyweight trong khi thread được gọi là lightweight process. Process nằm trong namespace System.Diagnostics.

Ví dụ chạy Notepad từ ứng dụng C#

using System; 
using System.Diagnostics; 

namespace DemoApplication { 
    class Program { 
        static void Main() { 
            Process notepad = new Process(); 
            notepad.StartInfo.FileName = "notepad.exe"; 
            notepad.StartInfo.Arguments = "DemoText.txt"; 
            notepad.Start(); 
            Console.ReadLine(); 
        } 
    } 
}

Output trên cho thấy console application mở Notepad với tên file DemoText được cung cấp trong arguments.

Ví dụ chạy Browser từ ứng dụng C#

using System; 
using System.Diagnostics; 

namespace DemoApplication { 
    class Program { 
        static void Main() { 
            Process.Start("https://www.google.com/"); 
            Console.ReadLine(); 
        } 
    } 
}

Code trên sẽ mở browser và điều hướng đến www.google.com.

ProcessStartInfo - Cấu hình chi tiết

using System; 
using System.Diagnostics; 

namespace DemoApplication { 
    class Program { 
        static void Main() { 
            var startInfo = new ProcessStartInfo { 
                FileName = "notepad.exe", 
                Arguments = "file.txt", 
                WindowStyle = ProcessWindowStyle.Maximized, // Maximized, Minimized, Hidden, Normal
                UseShellExecute = true,                      // Dùng shell execute (mặc định true)
                WorkingDirectory = @"C:\Temp",               // Thư mục làm việc
                Verb = "runas"                               // Run as administrator
            }; 
            
            Process process = Process.Start(startInfo); 
            
            // Đợi process kết thúc
            process.WaitForExit(); 
            Console.WriteLine($"Process exited with code: {process.ExitCode}"); 
            Console.ReadLine(); 
        } 
    } 
}

Chạy process và đọc output (Redirect Standard Output)

using System; 
using System.Diagnostics; 

namespace DemoApplication { 
    class Program { 
        static void Main() { 
            var startInfo = new ProcessStartInfo { 
                FileName = "cmd.exe", 
                Arguments = "/c dir", 
                UseShellExecute = false,           // Bắt buộc false để redirect
                RedirectStandardOutput = true,     // Redirect output
                RedirectStandardError = true,      // Redirect error
                CreateNoWindow = true              // Không tạo cửa sổ console
            }; 
            
            using (var process = Process.Start(startInfo)) { 
                string output = process.StandardOutput.ReadToEnd(); 
                string error = process.StandardError.ReadToEnd(); 
                process.WaitForExit(); 
                
                Console.WriteLine("Output:"); 
                Console.WriteLine(output); 
                if (!string.IsNullOrEmpty(error)) { 
                    Console.WriteLine("Error:"); 
                    Console.WriteLine(error); 
                } 
            } 
            Console.ReadLine(); 
        } 
    } 
}

Chạy process bất đồng bộ (Async)

using System; 
using System.Diagnostics; 
using System.Threading.Tasks; 

namespace DemoApplication { 
    class Program { 
        static async Task Main() { 
            var startInfo = new ProcessStartInfo { 
                FileName = "dotnet", 
                Arguments = "--version", 
                UseShellExecute = false, 
                RedirectStandardOutput = true 
            }; 
            
            using (var process = Process.Start(startInfo)) { 
                string version = await process.StandardOutput.ReadToEndAsync(); 
                await process.WaitForExitAsync(); 
                Console.WriteLine($".NET Version: {version.Trim()}"); 
            } 
        } 
    } 
}