.NET怎么在程序中执行一个外部exe文件_外部exe程序执行方法

来源:这里教程网 时间:2026-02-21 17:31:01 作者:

在 .NET 程序中执行外部 exe 文件,最常用的方式是使用 System.Diagnostics.Process 类。通过这个类可以启动、控制和与外部进程进行交互。下面介绍几种常见的用法。

1. 基本启动外部程序

使用 Process.Start() 方法可以直接启动一个外部 exe 文件:

using System.Diagnostics;
// 启动记事本
Process.Start("notepad.exe");

也可以指定完整路径:

Process.Start(@"C:\MyApp\myapp.exe");

2. 带参数启动外部程序

如果需要传递命令行参数,建议使用 ProcessStartInfo 来配置启动信息:

var startInfo = new ProcessStartInfo();
startInfo.FileName = @"C:\Tools\tool.exe";
startInfo.Arguments = "--input file.txt --output result.txt";
Process.Start(startInfo);

3. 隐藏窗口运行(后台执行)

如果你希望程序在后台运行而不弹出窗口,可以设置窗口样式为隐藏:

var startInfo = new ProcessStartInfo();
startInfo.FileName = "mybackground.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true; // 不创建窗口
Process.Start(startInfo);

4. 等待程序执行完成并获取返回值

有时候你需要等待外部程序执行完毕,并获取其退出码:

var process = Process.Start(startInfo);
process.WaitForExit(); // 等待结束
int exitCode = process.ExitCode;
Console.WriteLine($"程序退出码: {exitCode}");

5. 获取输出内容(控制台程序)

如果外部 exe 是控制台程序并输出文本,你可以重定向标准输出:

var startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c dir";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
using (var process = Process.Start(startInfo))
{
    string output = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
    Console.WriteLine(output);
}

注意:启用重定向时必须设置 UseShellExecute = false

6. 错误处理

执行外部程序时可能会遇到文件不存在或权限问题,建议加上异常处理:

try
{
    Process.Start("nonexistent.exe");
}
catch (Exception ex)
{
    Console.WriteLine("启动失败: " + ex.Message);
}
基本上就这些常见用法。根据实际需求选择是否需要参数、隐藏窗口、读取输出或等待完成。关键是灵活使用 ProcessStartInfo 来配置启动行为。

相关推荐