如何在C#代码中运行一个EXE文件?

226

我的C#项目中有一个EXE文件的引用。我该如何从我的代码中调用这个EXE文件?

4个回答

374
using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("C:\\");
    }
}

如果您的应用程序需要命令行参数,请使用类似如下的方法:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
        // For the example
        const string ex1 = "C:\\";
        const string ex2 = "C:\\Dir";

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
             // Log error.
        }
    }
}

2
"startInfo.UseShellExecute = false" 是一个很棒的东西...它对我非常有效!谢谢! :) - RisingHerc
@logganB.lehman 进程在 exeProcess.WaitForExit() 处永远挂起,有什么想法? - Dragon

20

你能否让你的回答更全面一些?或者指出重复的内容? - Peter Mortensen

18

例子:

System.Diagnostics.Process.Start("mspaint.exe");

编译代码

复制代码并将其粘贴到控制台应用程序的Main方法中。将“mspaint.exe”替换为要运行的应用程序的路径。


16
这样做与已有的答案相比如何提供更多价值?被采纳的答案还展示了Process.Start()的用法。 - default
5
没问题,我可以帮助初学者提供简化、分步骤、有许多细节剥离的示例。使用大写字母也是可以的 :P - DukeDidntNukeEm
2
我只需要一个快速执行exe的方法,这真的很有帮助。谢谢 :) - Sushant Poojary

10

示例:

Process process = Process.Start(@"Data\myApp.exe")
int id = process.Id
Process tempProc = Process.GetProcessById(id)
this.Visible = false
tempProc.WaitForExit()
this.Visible = true

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接