Skip to content
Amal Hashim
All posts
Snippet

SharePoint - Change a workflow task owner using C#

Reassign an existing SharePoint 2010 workflow task to a different user with SPWorkflowTask.AlterTask.

1 min read#C##SharePoint#SharePoint 2010

A workflow has created a task and it is assigned to the wrong person. You can change the owner from code with SPWorkflowTask.AlterTask.

Here the task is assigned to a normal user:

Workflow task assigned to the original user

The snippet below finds the tasks of a list item and assigns them to the Administrator account.

csharp
using (SPSite site = new SPSite("http://myteamsite:2012/"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPUser user = web.SiteUsers["myad\\administrator"];
        SPListItem taskItem = web.Lists["Shared Documents"].Items[0];

        SPWorkflowTaskCollection taskCollection =
            new SPWorkflowTaskCollection(taskItem, new SPWorkflowFilter());

        foreach (SPWorkflowTask task in taskCollection)
        {
            Hashtable ht = new Hashtable();
            ht[SPBuiltInFieldId.AssignedTo] = user;
            SPWorkflowTask.AlterTask((task as SPListItem), ht, true);
        }
    }
}

After running it, the task shows the new owner:

Workflow task now assigned to Administrator