尝试通过WinForms中的C#关闭exe时拒绝访问

时间:2018-10-02 09:33:52

标签: c# winforms

我通过Windows窗体应用程序打开和关闭应用程序,但问题是,我收到拒绝访问错误。

这是项目中的代码段。

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);
}

这是关闭的EXE方法:

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);
        }
    }
}

错误详细信息包括

  1. 消息:访问被拒绝
  2. ErrorCode:-2147467259

我发现我在关闭应用程序时正在创建问题。

1 个答案:

答案 0 :(得分:2)

根据documentation

  

Kill方法异步执行。叫杀之后   方法,调用WaitForExit方法以等待进程退出,   或检查HasExited属性以确定该进程是否具有   退出。

  

如果在进程当前正在调用Kill方法   终止时,将为访问被拒绝抛出Win32Exception。

问题在于您两次调用Kill,而第二次调用引发异常。 因此,解决方案是致电:

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