You can set
alreadyPresentTask.Definition.Settings.Enabled = true
. This will ensure the task is enabled and you do not have to set the
is a bit of a risky method in that it is non-deterministic. It will return the first task in any folder it finds whose name matches the one provided to the method. You are much safer to use the
method and provide the full path to the task as it is deterministic. Also, either your
if (action is ExecAction)
if (null == execAction)
statement is unnecessary as they both check the same condition.
I believe the problem is related to how C# handles references and potentially the wrapper not accommodating that well. To resolve, I would try something like:
// 1. If using the local instance of the Task Scheduler, you can use the static Instance property.
// 2. Prepend the exact folder name in GetTask.
var alreadyPresentTask = TaskService.Instance.GetTask("\\" + settings.TaskSchedulerTaskName);
if (alreadyPresentTask != null)
// 3. Avoid re-registering the task if not needed.
bool changed = false;
for (int i = 0; i < alreadyPresentTask.Definition.Actions.Count; i++)
ExecAction execAction = alreadyPresentTask.Definition.Actions[i] as ExecAction;
if (execAction != null)
var root = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var newPath = System.IO.Path.Combine(root, Path.GetFileName(execAction.Path));
// 4. I believe that by creating a new action and replacing the old you
// will avoid the reference problem.
alreadyPresentTask.Definition.Actions[i] = new ExecAction(newPath, execAction.Arguments, root);
changed = true;
// 5. Using this setting will ensure the task stays enabled
alreadyPresentTask.Definition.Settings.Enabled = true;