如何通过C#程序运行外部程序?

47

我该如何通过C#程序运行外部程序,比如记事本或计算器?


4
欢迎来到Stack Overflow。我想可以假设你的母语不是英语。 为了增加获取答案的机会,建议将问题标题改为“如何从C#程序打开外部程序?”同时请说明这是控制台应用程序、WinForms还是Web应用程序(希望不是后者)。提供更多信息,并确保查看Stack Overflow FAQ。 - Marko
@Michael 我认为hw只是how的简写。 - Mathias
1
可能是如何从C#启动进程?的重复问题。 - Gustavo Mori
4个回答

62

也许这会对你有所帮助:

using(System.Diagnostics.Process pProcess = new System.Diagnostics.Process())
{
    pProcess.StartInfo.FileName = @"C:\Users\Vitor\ConsoleApplication1.exe";
    pProcess.StartInfo.Arguments = "olaa"; //argument
    pProcess.StartInfo.UseShellExecute = false;
    pProcess.StartInfo.RedirectStandardOutput = true;
    pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    pProcess.StartInfo.CreateNoWindow = true; //not diplay a windows
    pProcess.Start();
    string output = pProcess.StandardOutput.ReadToEnd(); //The output result
    pProcess.WaitForExit();
}

13
请记得处理进程或在 using(Process pProcess = new Process()) { } 块中使用它。 - pKami

32

请注意,“Example”是一个无效链接。这往往是指定链接时的缺点。 - AndersK
也许只是我的视力不好。 - AndersK
2
不是指它没有任何作用,而是指它没有实际的示例。 - AndersK

15

这是一个简单的控制台应用程序,用于调用记事本.exe,请使用此程序进行检查。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Demo_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            Process ExternalProcess = new Process();
            ExternalProcess.StartInfo.FileName = "Notepad.exe";
            ExternalProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
            ExternalProcess.Start();
            ExternalProcess.WaitForExit();
        }
    }
}

13
例如像这样:

// run notepad
System.Diagnostics.Process.Start("notepad.exe");

//run calculator
System.Diagnostics.Process.Start("calc.exe");

请按照 Mitch 回答中的链接进行操作。


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