c# - 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
- message : Access is denied
- ErrorCode : -2147467259
I have found that it is creating problem when I am closing the application.
解决方案
根据文档:
Kill 方法异步执行。调用Kill方法后,调用WaitForExit方法等待进程退出,或者查看HasExited属性判断进程是否退出。
和
如果在进程当前终止时调用 Kill 方法,则会为 Access Denied 引发 Win32Exception。
问题是您两次调用 Kill 并且第二次调用引发异常。因此,解决方案是调用:
process.Kill();
process.WaitForExit();
推荐阅读
- mysql - 如果一个值被另一个表中的范围覆盖,则 MySQL 更新列
- scala - Scala条件累加
- excel - 在打开 excel 而不是更改值时执行 VBA 代码
- .htaccess - 不同用户的假子域,同时仍然浏览相同的文件夹结构
- django - 从 FullCalendar 和 Django 中删除事件
- javascript - 使用 div 和脚本的另一个 HTML 代码块更改内部 HTML
- swift - 如何创建apple watchOS5 并发症?
- octave - Octave 4.4.1 无法在 32 位 Windows 7 上启动
- angularjs - 如何为第二个控制器测试 mdDialog w/o mock?
- c# - 编辑下拉列表不显示模型的值