I opening and closing an application through my windows form application but the problem is, I am getting Access denied error.
Here is the code snippet from the project.
try
{
//This loop wil check the timing.
for (int i = 0; i < exeStartTimes.Count; i++)
{
if (hour == exeStartTimes[i].hour && minute == exeStartTimes[i].minute)
{
if (CheckExeIsOpen(tbExeName.Text) == false)
{
Process p = new Process();
p.StartInfo.FileName = (tbExeLocation.Text + tbExeName.Text);
p.Start();
AppendLogFile("Started " + tbExeLocation.Text + tbExeName.Text + " on " + time);
}
}
if (hour == exeEndTimes[i].hour && minute == exeEndTimes[i].minute)
{
if (CheckExeIsOpen(tbExeName.Text) == true)
{
CloseExe(tbExeName.Text);
AppendLogFile("Closed " + tbExeName.Text + time);
}
}
}
}
catch (Win32Exception w)
{
MessageBox.Show("Error occured : " + w.Message);
AppendLogFile("message : " + w.Message);
AppendLogFile("ErrorCode : " + w.ErrorCode.ToString());
AppendLogFile("Native : " +w.NativeErrorCode.ToString());
AppendLogFile("StackTrace : " + w.StackTrace);
AppendLogFile("Source : " + w.Source);
Exception e = w.GetBaseException();
AppendLogFile(e.Message);
}
And here are the close EXE methods:
private bool CheckExeIsOpen(string exeName)
{
string name = exeName.Split('.')[0];
foreach (var process in Process.GetProcesses())
{
if (process.ProcessName == name)//process name matched return true appliation is open
{
return true;
}
}
return false;//process name not matched return false appliation is closed
}
private void CloseExe(string exeName)
{
string name = exeName.Split('.')[0];
foreach (var process in Process.GetProcesses())
{
if (process.ProcessName == name)
{
process.Kill();
AppendLogFile(tbExeName.Text + " Closed on " + DateTime.Now);
}
}
}
The error details include
I have found that it is creating problem when I am closing the application.
According to the documentation:
The Kill method executes asynchronously. After calling the Kill method, call the WaitForExit method to wait for the process to exit, or check the HasExited property to determine if the process has exited.
and
If the call to the Kill method is made while the process is currently terminating, a Win32Exception is thrown for Access Denied.
The problem is that you call Kill twice and second call throws exception. So, the solution would be to call:
process.Kill();
process.WaitForExit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With