This is to show the basic outline of code to add an attachment to a list in sharepoint, I made a page with System.Web.UI.WebControls.FileUpload on it and used the control’s FileBytes property to get an array of bytes. so the call to this function will look like this 

addAttachment("title text","filename.txt",fileuploadControl.FileBytes);

the code to add the attacment to the list will look like this

public static void addAttachment(string title,string filename,byte[] fil)
{

        using (SPSite site = new SPSite("https://site"))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPList list = web.Lists["SomeList"];
                SPQuery query = new SPQuery { RowLimit = 0 };
                SPListItem listItem = list.GetItems(query).Add();
                listItem.Web.AllowUnsafeUpdates = true;

                //title field in the list
                listItem.Title = title;

                //add the attachment to the list
                SPAttachmentCollection attachments = listItem.Attachments;
                attachments.Add(filename, fil);

                listItem.Update();
                list.Update();
                web.Update();
            }
        }
}

basicly, you query the list with rowlimit = 0 to avoid to get all items in the items object, and then use the SPAttachmentCollection to add the file you want to attach with the appropriate filename.

Advertisement