เรียกใช้ exe จากรหัส C #


163

ฉันมีไฟล์ exe อ้างอิงในโครงการ C # ของฉัน ฉันจะเรียก exe นั้นจากรหัสของฉันได้อย่างไร

คำตอบ:


287
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 (); ความคิดใด ๆ
Dragon


11

ตัวอย่าง:

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

รวบรวมรหัส

คัดลอกรหัสและวางลงในวิธีการหลักของแอปพลิเคชันคอนโซล แทนที่ "mspaint.exe" ด้วยพา ธ ไปยังแอปพลิเคชันที่คุณต้องการเรียกใช้


15
สิ่งนี้ให้คุณค่ามากกว่าคำตอบที่สร้างไว้แล้วได้อย่างไร คำตอบที่ได้รับการยอมรับยังแสดงให้เห็นถึงการใช้งานProcess.Start()
เริ่มต้น

3
ดังนั้น - มันก็โอเคที่จะช่วยผู้เริ่มต้นด้วยตัวอย่างง่าย ๆ ทีละขั้นตอนโดยมีรายละเอียดมากมายหลุดออกไป ยังตกลงที่จะใช้ตัวพิมพ์ใหญ่: P
DukeDidntNukeEm

ฉันต้องการวิธีที่รวดเร็วในการเรียกใช้ exe และมันมีประโยชน์จริงๆ ขอขอบคุณ :)
สุสา Poojary

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;

2

ฉันรู้ว่านี่เป็นคำตอบที่ดี แต่ถ้าคุณสนใจฉันเขียนไลบรารีที่ทำให้การเรียกใช้คำสั่งง่ายขึ้นมาก

ตรวจสอบออกที่นี่: https://github.com/twitchax/Sheller

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.