Executing External EXE Files within C# Applications
This guide demonstrates how to launch executable (EXE) files from your C# program using the power of the .NET Framework's Process
class.
The simplest method involves the Process.Start()
method, which takes the EXE file's path as a string argument. For example, to run C:\path\to\myprogram.exe
, use:
<code class="language-csharp">using System.Diagnostics; class Program { static void Main() { Process.Start("C:\path\to\myprogram.exe"); } }</code>
For EXEs needing command-line arguments, leverage the ProcessStartInfo
class for finer control. This example showcases its capabilities:
<code class="language-csharp">using System.Diagnostics; class Program { static void Main() { RunExternalAppWithArguments(); } static void RunExternalAppWithArguments() { // Example paths (replace with your actual paths) const string outputDir = "C:\OutputDirectory"; const string inputFile = "C:\InputFile.txt"; // Configure process settings ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; // Show the console window startInfo.UseShellExecute = false; // Required for argument handling startInfo.FileName = "myCommandLineApp.exe"; // Your EXE file startInfo.Arguments = $"-o \"{outputDir}\" -i \"{inputFile}\""; // Arguments try { using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); // Wait for the EXE to finish } } catch (Exception ex) { // Handle exceptions appropriately (log the error, etc.) Console.WriteLine($"Error launching EXE: {ex.Message}"); } } }</code>
Remember to replace placeholder paths and filenames with your actual values. Error handling is crucial for robust applications. This improved example provides more context and best practices for launching external processes.
The above is the detailed content of How Can I Execute an EXE File from My C# Application?. For more information, please follow other related articles on the PHP Chinese website!