3

我正在寻找使用 Process.Start() 来启动可执行文件,但我想继续执行程序,无论可执行文件是成功还是失败,或者 Process.Start() 本身是否引发异常。

我有这个:

        myProcess.StartInfo.UseShellExecute = false;
        // You can start any process, HelloWorld is a do-nothing example.
        myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.Start();

我知道您可以将其添加到 try catch

          try
        {
            myProcess.StartInfo.UseShellExecute = false;
            // You can start any process, HelloWorld is a do-nothing example.
            myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.Start();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

如果找不到文件,尝试捕获版本不会失败?如何处理其他异常,如 InvalidOperationException Win32Exception ObjectDisposedException

如果失败,目标只是继续使用代码......

非常感谢!

4

1 回答 1

7

捕获异常应该保留给您期望永远不会发生但可能发生的不测事件。相反,您可以尝试先检查文件是否存在

var filePath = @"C:\HelloWorld.exe";
if(File.Exists(filePath))
{
     myProcess.StartInfo.UseShellExecute = false;
     // You can start any process, HelloWorld is a do-nothing example.
     myProcess.StartInfo.FileName = filePath ;
     myProcess.StartInfo.CreateNoWindow = true;
     myProcess.Start();
}

编辑

如果您想格外小心,您也可以始终使用 try catch 但捕获特定异常。

try
{
//above code
}
catch(Win32Exception)
{
}

编辑2

var path = new Uri(
  Path.Combine((System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath,
           "filename.exe"));

最终编辑

当捕获到异常时,您的程序进入 catch 块以允许您采取相应措施,大多数程序倾向于在其中包含某种错误日志记录,因此如果可能,可以纠正此错误/错误。暂时你只包含一条消息让用户知道发生了意外情况可能是值得的

catch(Win32Exception)
{
MessageBox.Show(this, "There was a problem running the exe");
}
于 2013-07-31T21:55:27.027 回答