首页 > 解决方案 > Access is denied when trying to close an exe through C# in winforms

问题描述

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

  1. message : Access is denied
  2. ErrorCode : -2147467259

I have found that it is creating problem when I am closing the application.

标签: c#winforms

解决方案


根据文档

Kill 方法异步执行。调用Kill方法后,调用WaitForExit方法等待进程退出,或者查看HasExited属性判断进程是否退出。

如果在进程当前终止时调用 Kill 方法,则会为 Access Denied 引发 Win32Exception。

问题是您两次调用 Kill 并且第二次调用引发异常。因此,解决方案是调用:

process.Kill(); 
process.WaitForExit();

推荐阅读