Friday, October 19, 2007

Add new document to Document Library in SharePoint using C#

          We are exploring SharePoint 2007 from last few days. Here is the code for adding new document to document library using C#.  I have created a page with a file upload control and a button. When user clicks on button the selected document will be uploaded to specific document library. You need to add reference to Microsoft.SharePoint DLL to make this code running.

if (FileUpload1.PostedFile != null)
            if(FileUpload1.PostedFile.ContentLength > 0)
                   System.IO.Stream strm =

                   byte[] byt = new byte[
Convert.ToInt32 (

                   strm.Read(byt, 0, Convert.ToInt32


                // Open site where document library is created.
                using (SPSite objSite = new SPSite
                    using (SPWeb objWeb = objSite.OpenWeb())
                        SPFolder mylibrary = objWeb.Folders["Name of
                                                     Document Library"

                        // Set AllowUnsafeUpdates = true to avoid
                        // security error
                        objWeb.AllowUnsafeUpdates = true;

                               (FileUpload1.PostedFile.FileName), byt);

     Above code first reads the uploaded file in Stream and than uploads it on document library.

Happy Programming !!!

No comments: