Thursday, December 8, 2016

SharePoint 2010 - Uploading a document into a document library with C# and Microsoft.SharePoint

Still working with 2010 in 2016? Me too.

You need to reference these libraries:

using Microsoft.SharePoint;
using System.IO;



        private static void uploadDocument()
        {
            String fileToUpload = @"C:\Temp\Accessibility audit of SharePoint 2010 January 2013.docx";
            String sharePointSite = "SharePoint site URL";
            String documentLibraryName = "Name of document library";
            try
            {
                using (SPSite oSite = new SPSite(sharePointSite))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        if (!System.IO.File.Exists(fileToUpload))
                            throw new FileNotFoundException("File not found.", fileToUpload);

                        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

                        // Prepare to upload
                        Boolean replaceExistingFiles = true;
                        String fileName = System.IO.Path.GetFileName(fileToUpload);
                        FileStream fileStream = System.IO.File.OpenRead(fileToUpload);

                        // Upload document
                        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
                        // 2/12/2013 12:15 PM
                        spfile.Item.Properties.Clear();
                        spfile.Update();

                        // Commit
                        myLibrary.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

No comments: