How To Add Document To A SharePoint Document Library C#



TODO:

Have you ever wanted to add a document to a SharePoint document library?  The below example, is a method that will allow you to do just that.

 

SOLUTION:

        /// <summary>
        /// Add the contents of a file to a document library
        /// </summary>
        /// <param name="DocumentData">byte[] of the document data</param>
        /// <param name="SharePointUrl">The URL to the sharepoint server</param>
        /// <param name="SharePointSite">The name of the site the document library resides</param>
        /// <param name="DocumentLibrary">The name of the document library</param>
        /// <param name="MetaData">Any meta data you want to add.  For instance if there are other columns, you can specify them here.</param>
        /// <param name="OverWriteFile">Overwrite flag.  true or false, self explanatory</param>
        /// <returns></returns>
        public bool AddFileToDocumentLibrary(byte[] DocumentData, string SharePointUrl, string SharePointSite, string DocumentLibrary, Hashtable MetaData, bool OverWriteFile)
        {
            try
            {
                //get the site
                using (SPSite mysiteCollection = new SPSite(SharePointUrl))
                {
                    //get web info by title (i need to do it this way)
                    SPWebInfo webinfo = mysiteCollection.AllWebs.WebsInfo.Find(delegate(SPWebInfo w) { return w.Title.ToUpper() == SharePointSite.ToUpper(); });
                    
                    //get the site by title (need to because name could be site/site...)              
                    using (SPWeb rootSite = mysiteCollection.AllWebs[webinfo.Id])   //now get the web by GUID
                    {
                        SPFile newFile = null;
                        SPFolder incompleteLibrary = rootSite.Folders[DocumentLibrary]; //the list by display name
                        
                        //now create a hash of our fields we want to set, and do it in one shot.
                        if (MetaData == null || MetaData.Count == 0)
                            newFile = incompleteLibrary.Files.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData, OverWriteFile);  //add it to the library
                        else
                            newFile = incompleteLibrary.Files.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData, MetaData, OverWriteFile);  //add it to the library
                    }
                }
                
                return true;
            }
            catch (Exception x)
            {
                return false;
            }
        }

 

NOTES:

In my case, I was only adding XML files.  Therefore you can change the file name generation to use an extension that is passed in potentially.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading