3

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.

jpaugh
  • 6,634
  • 4
  • 38
  • 90
user1162880
  • 31
  • 1
  • 2
  • Can you please post the code from your button click event (The stuff that is trying to add the document) – undefined Jan 22 '12 at 05:12

1 Answers1

0
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;
                    }
                }
            }
        }
    }                          
}
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51