Build a C # Windows application that can open applications

Recently, I had the idea to create a C # application for Windows Form, which allows the user to run applications from there. This is my "raw" code:

Button1 Click Event ...

{ System.Diagnostics.Process.Start("WINWORD.EXE"); } 

Button2 Click Event ...

 { System.Diagnostics.Process.Start("WINRAR.EXE"); } 

. ,,,,.

and much more...

Can someone please tell me what is the code that processes the event in case the application cannot be found (for example, WINWORD.EXE is unavailable blah, blah blah)?

I tried using the "if-statement", but to no avail, I get compilation errors.

Can someone help me? How to create a function that allows the user to add an application shortcut to a C # application?

Thanks to everyone in advance.

+4
source share
4 answers

I would just put your call to run the application in a try...catch...

Button2 Click Event ...

 { try { System.Diagnostics.Process.Start("WINRAR.EXE"); } catch(Exception exc) { // handle exception, eg possibly log it to a file or database, or do something else MessageBox.Show(exc.Message, "Error occured", MessageBoxButtons.OK, MessageBoxIcon.Error); } } 

In this case, no matter what goes wrong, you can catch this case and at least show the message to the user - of course, you can "configure" this message a little ....

0
source
 System.IO.File.Exists("your file path"); 

returns true if the file exits

 if(System.IO.File.Exists("your file path")) { //Do something } else { OpenFileDialog _File = new OpenFileDialog()) _File.ShowDialog(); // this will open a filedialog box to browse } 
+3
source

Use System.IO.File.Exists to check the file path or use the try..catch.. block to handle exceptions.

 try { System.Diagnostics.Process.Start("WINWORD.EXE"); }catch(Exception ex) { MessageBox.Show(ex.getMessage()); } 
+2
source

It’s best to “look before you jump” and check the PATH system and the registry for the file, but this is much more complicated than it might seem. For example, on my computer, Microsoft Office was not found along the way.

The simplest is checking for a System.ComponentModel.Win32Exception :

 try { Process.Start("filename.exe"); } catch (System.ComponentModel.Win32Exception ex) { if (ex.NativeErrorCode == 2) { // file was not found, so do something } } 

By explicitly checking the correct underlying exception, you guarantee that your system will still stop if something happens other than when the file is not found. Also, by checking for error code 2, you know that your system must work with versions of Windows using languages ​​other than English.

0
source

Source: https://habr.com/ru/post/1383378/


All Articles