How to execute an EXE executable or a BAT file from .NET code?

-------------------------------------------------------
Goto blog home
Visit my new blog dedicated to Internet of Things, Embedded Programming & Automation
-------------------------------------------------------
The following code will allow you to invoke and execute an executable file from your program (here it has been written in C#). The WaitForExit() function provides your program control with the capability of synchronous execution. Refer to the 'System.Diagnostics' assembly for utilizing the 'Process' object.

public bool RunExecutable(string strExePath)
{
bool _bSuccess = true; //Assume by default that the executable will run successfully
Process _objProcess = new Process();
_objProcess.EnableRaisingEvents = false;
_objProcess.StartInfo.FileName = strExePath; //Eg, D:\Test\TestProg.exe
try
{
_objProcess.Start();
_objProcess.WaitForExit();
}
catch(Exception e)
{
//If any exception happens during attempted run
_bSuccess = false;
}
return _bSuccess;
}

No comments:

Post a Comment