3

I'm looking to use Process.Start() to launch an executable, but I want to continue program execution regardless of whether the executable succeeds or fails, or whether Process.Start() itself throws an exception.

I have this:

        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();

I know you can add this into 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);
        }

Try catch version will not fail if file not found? How to go with other exception like InvalidOperationException Win32Exception ObjectDisposedException

The goal is just to continue with the code if this fail...

Thanks a lot!

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 に答える