Esegui un exe dal codice C #


163

Ho un riferimento al file exe nel mio progetto C #. Come invoco quell'exe dal mio codice?

Risposte:


287
using System.Diagnostics;

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

Se l'applicazione richiede argomenti cmd, utilizzare qualcosa del genere:

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è stata una cosa fantastica ... Ha funzionato per me come un incantesimo! Grazie! :)
RisingHerc

Il processo @ logganB.lehman si blocca per sempre su exeProcess.WaitForExit (); qualche idea?
Drago


11

Esempio:

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

Compilazione del codice

Copia il codice e incollalo nel metodo principale di un'applicazione console. Sostituire "mspaint.exe" con il percorso dell'applicazione che si desidera eseguire.


15
In che modo questo fornisce più valore delle risposte già create? La risposta accettata mostra anche l'uso diProcess.Start()
Default

3
Quindi, va bene aiutare un principiante con esempi semplificati e passo dopo passo con molti dettagli eliminati. Va bene anche usare i tappi: P
DukeDidntNukeEm

Avevo solo bisogno di un modo rapido per eseguire l'exe e questo è stato davvero utile. Grazie :)
Sushant Poojary,

7

Esempio:

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

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.