如何从C#代码中删除计划任务

如何从C#代码中删除计划任务

问题描述:

我使用下面的C#Code在Windows 2008 Server中创建了Schedule Task.It工作正常,但当我从C#Code.Its删除任务时显示错误消息访问被拒绝。(例外来自HRESULT:0X80070005( E_ACCESSDENIED)



请查看以下代码并告知如何操作..



创建任务: - (它工作正常)



I have created Schedule Task in Windows 2008 Server using below C# Code.It works fine but when I Delete Task from C# Code.Its shows an error message as "Access is Denied. (Exception from HRESULT : 0X80070005 (E_ACCESSDENIED) "

Please check below code and advise how to do that..

Creating Task :- (It works fine)

private void CreateTask(string StrTaskName,string  StrDate)
     {
         using (TaskService ts = new TaskService())
         {
             TaskDefinition td = ts.NewTask();
             td.RegistrationInfo.Description = "SMS Alert System";
             td.Principal.LogonType = TaskLogonType.InteractiveToken;

             TimeTrigger dt = (TimeTrigger)td.Triggers.Add(new TimeTrigger());
             dt.StartBoundary = Convert.ToDateTime(StrDate);

             string doubleQuotedPath = string.Format(@"""{0}""", StrTaskName);
             td.Actions.Add(new ExecAction(@"D:\Alert\SMSAlertSystem.exe", doubleQuotedPath, null));
             ts.RootFolder.RegisterTaskDefinition(StrTaskName, td);


         }
     }







删除任务: - (不工作)






Deleting Task :- (Not working)

using (TaskService ts = new TaskService())
{
    ts.RootFolder.DeleteTask(StrtMessage.Trim());
}





我尝试过:



我已经尝试了上面的代码,但没有解决...



What I have tried:

I have tried above code,but not solved...

Google是你的朋友:好好经常拜访他。他可以比在这里发布问题更快地回答问题...



在MSDN上发现一个非常快速的搜索: TaskFolder.DeleteTask总是返回Access Denied [ ^ ]这说明任务只能由管理员删除,并提供高程代码。您的用户需要同意阿联酋的请求才能将其删除。



将来,请尝试自己做至少基础研究,不要浪费时间或我们的。
Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here...

A very quick search found this on MSDN: TaskFolder.DeleteTask always returns Access Denied[^] Which explains that tasks can only be deleted by admins, and gives the elevation code. Your user will need to agree to the UAE request in order to delete it.

In future, please try to do at least basic research yourself, and not waste your time or ours.