Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Process.Start() Continue On If File Not Found?

Tags:

c#

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!

like image 528
Boris Daka Avatar asked Dec 05 '25 03:12

Boris Daka


1 Answers

catching exceptions should be reserved for the eventualities you expect to never happen but could possibly happen. instead you can try checking if the file exists first

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

Edit

If you want to be extra cautious, you could always use the try catch also but catch the specific exceptions.

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

Edit2

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

Final edit

When an exception is caught, your program enters the catch block to allow you to act accordingly, most programs tend to include some kind of error logging into this so this error/bug can be rectified if possible. It may be worth for the time being you just including a message to let the user know something unexpected happened

catch(Win32Exception)
{
MessageBox.Show(this, "There was a problem running the exe");
}
like image 188
Sayse Avatar answered Dec 06 '25 16:12

Sayse