从C#代码运行exe


163

我的C#项目中有一个exe文件参考。如何从代码中调用该exe?

Answers:


286
using System.Diagnostics;

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

如果您的应用程序需要cmd参数,请使用以下命令:

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.
        }
    }
}

1
startInfo.UseShellExecute = false真是一件了不起的事情...对我来说就像是魅​​力!谢谢!:)
RisingHerc

@ logganB.lehman进程永久挂在exeProcess.WaitForExit();上 任何想法?


11

例:

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

编译代码

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


15
与已经创建的答案相比,这如何提供更多的价值?接受的答案还显示了Process.Start()
默认的

3
所以-可以帮助初学者使用简化的分步示例,其中包含许多详细信息。也可以使用大写字母:P
DukeDidntNukeEm '18

我只需要一种快速的方法来执行exe,这真的很有帮助。谢谢您:)
Sushant Poojary '19年

7

例:

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.