Cancelling a Running Workflow Programatically
I got asked recently how to cancel a running workflow, so I thought I'd post the solution here for everyone . . .
The first step is to get an instance of the SPWorkflow object that represents the workflow that is running on the SPListItem in question. This can be performed as follows:
foreach (SPWorkflow wf in listItem.Workflows)
if (wf.ParentAssociation.BaseId == <Guid from workflow.xml>)
if (wf.InternalState == SPWorkflowState.Running)
// Need to cancel wf here . . .
Once you've got the running SPWorkflow instance as indicated above, you now need to cancel it. This is performed by calling the CancelWorkflow method of the SPWorkflowManager class passing in the SPWorkflow instance: