从C#中启动一个应用程序(.EXE)?

187

如何使用C#启动应用程序?

要求: 必须在Windows XPWindows Vista上运行。

我见过一个来自DinnerNow.net示例的样本,但它只能在Windows Vista上运行。

9个回答

243

这是一个有用代码片段:

using System.Diagnostics;

// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments; 
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;


// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
     proc.WaitForExit();

     // Retrieve the app's exit code
     exitCode = proc.ExitCode;
}

你可以利用这些对象做更多的事情,你应该阅读文档:ProcessStartInfoProcess


8
我想指出的是,这种方法似乎适用于除了 .exe 以外的其他文件类型。只需指向要打开的文件,Windows 将尽力将其打开:System.Diagnostics.Process.Start(@"C:\Users\Blank\Desktop\PdfFile.pdf"); - DLeh
WindowStyle = ProcessWindowStyle.Hidden 是用于非GUI界面的。第一次运行时,如果没有设置 UseShellExecute = false,会失败,但现在可以正常工作了。不太清楚发生了什么... - Barton
如果我不知道exe的完整名称,我想调用“PathTo*.exe”,这是否可能?我可以使用“*”来代替名称的其余部分吗? - vishal
@vishal,这个过程是为了调用特定的可执行文件。你当然可以尝试使用PathTo*.exe,但我不会期望它能正常工作。(a) 如果有多个匹配项怎么办?(b) 我希望微软的代码不会允许这样做,因为这会造成弱安全性。 - sfuqua

184

使用System.Diagnostics.Process.Start() 方法。

查看这篇文章以了解如何使用它。

Process.Start("notepad", "readme.txt");

string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
              System.Windows.Forms.Application.ExecutablePath);

Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");

63
System.Diagnostics.Process.Start("PathToExe.exe");

如果我不知道 exe 的完整名称,我是否可以调用“PathTo*.exe”?这可能吗? - vishal
@vishal 你需要编写一个搜索可执行文件的过程。 - KADEM Mohammed

22
System.Diagnostics.Process.Start( @"C:\Windows\System32\Notepad.exe" );

18

如果你像我一样使用 System.Diagnostics 时遇到问题,可以使用以下简单的代码,而无需使用它:

using System.Diagnostics;

Process notePad = new Process();
notePad.StartInfo.FileName   = "notepad.exe";
notePad.StartInfo.Arguments = "mytextfile.txt";
notePad.Start();

11
这个“没有System.Diagnostics”的意思是什么?ProcessSystem.Diagnostics 中。 - Paul Sinclair

8

5

只需将您的 file.exe 文件放入 \bin\Debug 文件夹中,然后使用以下命令:

Process.Start("File.exe");

4
你的回答如何超越之前的所有回答? - mustaccio
1
大多数来看这篇文章的人都会对文件路径感到困惑,通常他们会将文件放在调试文件夹中,因此当他们直接使用我的提示“File.exe”时,就不需要在这种情况下指定路径。 - Amin Mohamed

2
使用 Process.Start 启动一个进程。
using System.Diagnostics;
class Program
{
    static void Main()
    {
    //
    // your code
    //
    Process.Start("C:\\process.exe");
    }
} 

1

试试这个:

Process.Start("Location Of File.exe");

请确保使用 System.Diagnostics 库。


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