Mohamed Ali Bouhoum
Mohamed Ali Bouhoum

Reputation: 81

Check if the process exists before process.start();

I made a little program that execute executable file (.exe) but when you write down no existed file I get an error, the file specific not found.

So I'm wondering if there's a way to check if the process exists first before running it, and if it doesn't exist you can show a message box.

This is my code

 private void btn_Start_Click(object sender, EventArgs e)
    {


        string text = textBox1.Text;
        Process process = new Process();
        if (!textBox1.Text.Contains(".exe"))
        {
            process.StartInfo.FileName = text + ".exe";
        }
        else
        {
            process.StartInfo.FileName = text;
        }
        process.Start();


    }

Upvotes: 1

Views: 4540

Answers (2)

Koeman
Koeman

Reputation: 1

Please try the following code: ->(You have to add #using System.IO; before using "File.Exists" command)

button1_Click(object sender, EventArgs )
{
            string exepath = "C:\\example\\example.xlsx";
            if(File.Exists(exepath))
            {
                Process.Start(exepath);
            }
            else
            {
                MessageBox.Show("File not found!");
            }
}

Hope it's working !

You can string the path and string the filename in other string, and then you can even check the Folder, and if the folder exists ,then check the file! Also you can use your textbox1 as filename, but you have to add the path, unless it will be search in the program directory.(bin/debug) If i was wrong, forgive me, i am learning c# at the moment! Have a good day!

Upvotes: 0

alexmac
alexmac

Reputation: 19617

Check that file is exists before start process:

var processFileName = !textBox1.Text.Contains(".exe")
    ? text + ".exe"
    : text;

if (File.Exists(processFileName))
{
    Process process = new Process();
    process.Start(processFileName);
}

Upvotes: 2

Related Questions