Saturday, 1 October 2016

Uploading files to SharePoint from Local system programatically

Hi guys,

In this post I am going to describe how to write a console application that will upload all files present in a particular directory into SharePoint.

You would need to install the SharePoint client Dlls to use the SharePoint 2010 SDK.
These Dlls are required and can be downloaded from here:
Microsoft.SharePoint.Client
Microsoft.SharePoint.Client.Runtime

The main method that gets the files from the location and uploads them into SharePoint is as below:
 public static void Main(string[] args)
        {
            var pricingDocuments = Directory.GetFiles("C:\\Users\\anurag\\Desktop");
            // Attach the files obtained to the product
            var defaultSiteUrl = "http://192.168.85.9/";
            var sharePointUser = "USER_NAME";
            var sharepointPassword = "PASSWORD";
            var sharepointDomain = "DOMAIN";
            const string baseFolderName = "product";

            using (var clientContext = new ClientContext(defaultSiteUrl))
            {
                clientContext.Credentials = new NetworkCredential(sharePointUser, sharepointPassword, sharepointDomain);
                Web web = clientContext.Web;

                var allProductsFolder = web.GetFolderByServerRelativeUrl(defaultSiteUrl + baseFolderName);
                clientContext.Load(allProductsFolder, i => i.Folders);
                clientContext.ExecuteQuery();
                var productFolders = allProductsFolder.Folders;
                Console.WriteLine("The number of folders inside is: " + productFolders.Count);
                if (productFolders != null)
                {
                   // file name will be of this format: Alpha_257B6BB3AFC54E13B5B68DE92C7F64D3
                    var requiredFolderName = "Alpha" + "_" + Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper();
                   
                    Folder requiredFolder = null;
                    try
                    {
                        requiredFolder =
                            web.GetFolderByServerRelativeUrl(defaultSiteUrl + baseFolderName + "/" + requiredFolderName);
                        clientContext.Load(requiredFolder);
                        clientContext.ExecuteQuery();                                              
                        Console.WriteLine("Created");
                    }
                    catch (ServerException ex)
                    {
                        if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
                        {
                                // the required folder does not exist - so create it                          
                                requiredFolder = allProductsFolder.Folders.Add(requiredFolderName);
                                clientContext.Load(requiredFolder);
                                clientContext.ExecuteQuery();                          
                        }
                        else
                        {
                            // some other exception - yikes!
                            throw;
                        }
                    }

                    foreach (var pricingDocumentWithLocation in pricingDocuments)
                    {
                        var fileName = Utility.GetFileName(pricingDocumentWithLocation);
                        var fileContents = File.ReadAllBytes(pricingDocumentWithLocation);
                        var fci = new FileCreationInformation();
                        fci.Content = fileContents;
                        fci.Url = fileName;
                        fci.Overwrite = true;
                        var fileToUpload = requiredFolder.Files.Add(fci);
                        clientContext.Load(fileToUpload);
                        clientContext.ExecuteQuery();
                    }
                }
            }          
        }

The parts highlighted above need to be replaced according to the required SharePoint instance/ local file system location adhering to the format to avoid any exception.

Hope this helps!

No comments:

Post a Comment