How to Add a Task in a SharePoint 2007 (MOSS/WSS) Site Programmatically

Here is a piece of code (a function) to add a task. You can use it as a Web Method in a custom Web Service. This method can be used from Applications outside of SharePoint, provided the user using this application has sufficient privilege to update Tasks Lists.

public string CreateTask(string SitePath, string TaskName, string AssgnTo, DateTime DueDate)

    {

        string ReturnVal = "";

        try

        {

           SPSite WebApp = new SPSite(SitePath);

            SPWeb Site = WebApp.OpenWeb();

            SPList TaskList = Site.Lists["Tasks"];

            // add a new item…

            SPListItem NewTask = TaskList.Lists["Tasks"].Items.Add();

            NewTask["Priority"] = "(2) Normal";

            NewTask["Title"] = TaskName;

            NewTask["DueDate"] = DueDate;

            NewTask["Assigned To"] = Site.Users.GetByEmail(AssgnTo);

            NewTask.Update();

        }

        catch (Exception ex)

        {

            ReturnVal += "Task not added, reason: " + ex.Message;

        }

        return ReturnVal;

    }