Saturday, April 30, 2011

Programmatically adding a document to a document library

  public void AddDoctoLibrary()
        {
            if (FileUpload1.PostedFile != null)
            {
                if (FileUpload1.PostedFile.ContentLength > 0)
                {
                    Stream strm = FileUpload1.PostedFile.InputStream;
                    byte[] byt = new byte[Convert.ToInt32(FileUpload1.PostedFile.ContentLength)];
                    strm.Read(byt, 0, Convert.ToInt32(FileUpload1.PostedFile.ContentLength));
                    strm.Close();
                    // Open site where document library is created.
                    using (SPSite oSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb(SPContext.Current.Web.ID))
                        {
                            SPList lstMeetingDocuments = oWeb.Lists["Meeting Documents"];
                            oWeb.AllowUnsafeUpdates = true;
                            SPFile newfile = lstMeetingDocuments.RootFolder.Files.Add(Path.GetFileName(FileUpload1.PostedFile.FileName), byt);
                            SPListItem newItm = lstMeetingDocuments.GetItemById(newfile.Item.ID);
                            newItm["MeetingID"] = lblMID.Text;
                            newItm.Update();
                            lstMeetingDocuments.Update();
                        }
                    }
                }
            }

No comments:

Post a Comment