Add/Create new document in SharePoint document Library programmatically

8.8k views Asked by At

I have created a new Document Library and set up custom content type with MS Word Document Template. When i click on Create new template it works fine. but i need to be able to add some logic on a button event where it will go into that library and create a new document, so that when i go into that library i will see a new document that has been created by that button event.

i tried doing it as i would do a regular list item, but i got the following error on item.update:

To add an item to a document library, use SPFileCollection.Add()

Now i did some research but everywhere i see the code for uploading a file to the document library but no where i can find how to add a new document using my template that is associated in that doc library.

please help and thanks.

1

There are 1 answers

1
chandrasekar tovvala On
public static void colFileMtod()
{
    using (SPSite objsite = new SPSite("http://smi-dev.na.sysco.net/SyscoFinance/FSR/"))
    {
        using (SPWeb objWeb = objsite.OpenWeb())
        {
            SPFileCollection collFiles = objWeb.GetFolder("BPCPublishRecord").Files;
            SPList lst = objWeb.Lists["BPCPublishRecordCopy"];

            if (lst != null)
            {

                if (objWeb.Lists.Cast<SPList>().Any(list => list.Title.Equals("BPCPublishRecordCopy", StringComparison.OrdinalIgnoreCase)))
                {
                    foreach (SPFile file in collFiles)
                    {
                        string strDestUrl = collFiles.Folder.Url + "/" + file.Name;
                        byte[] binFile = file.OpenBinary();

                        SPUser oUserAuthor = file.Author;
                        SPUser oUserModified = file.ModifiedBy;
                        System.DateTime dtCreated = file.TimeCreated;
                        System.DateTime dtModified = file.TimeLastModified;

                        SPFile oFileNew = collFiles.Add(strDestUrl, binFile, oUserAuthor, oUserModified, dtCreated, dtModified);
                        SPListItem oListItem = lst.AddItem();
                        oListItem = oFileNew.Item;
                        oListItem["Created"] = dtCreated;
                        oListItem["Modified"] = dtModified;
                        oListItem.Update();
                        objWeb.AllowUnsafeUpdates = true;
                    }
                }
            }
        }
    }                          
}