Context: I am trying to upload a large number of files to a SharePoint library. I will call the library Library Name
here.
For simplicity, I will only be attempting to upload one file in the code that follows. The path to this file will be C:/Users/UserName/Desktop/Test.txt
I will call the SharePoint Site http://share-internal.CompanyName.com/Section/Subsection
Here is the code I am using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
namespace FilesToSharePointLibrary
{
class Program
{
static void Main(string[] args)
{
String fileToUpload = "C:/Users/UserName/Desktop/Test.txt";
String sharePointSite = "http://share-internal.CompanyName.com/Section/Subsection";
String libraryName = "Library Name";
String fileName = fileToUpload.Substring(fileToUpload.LastIndexOf("\\") + 1);
using(ClientContext context = new ClientContext(sharePointSite))
{
FileCreationInformation FCInfo = new FileCreationInformation();
FCInfo.Url = fileToUpload;
FCInfo.Overwrite = true;
FCInfo.Content = System.IO.File.ReadAllBytes(fileToUpload);
Web web = context.Web;
List library = web.Lists.GetByTitle(libraryName);
library.RootFolder.Files.Add(FCInfo);
context.ExecuteQuery();
}
Console.WriteLine("Success");
}
}
}
The issue I am having in the context.ExecuteQuery();
line.
When I attempt to add one file to the SharePoint Library, Library Name
I get the following Exception:
Microsoft.SharePoint.Client.ServerException: 'Value does not fall within the expected range.'
Things I have tried:
Library_x0020_Name
, but the exception changed, saying it could not find that list.This leads me to believe that I have the list name and site URL correct, So I am confused as to what could be causing issues at this point.
Please use SharePoint library folder url when setting FCInfo.Url property, I modify the code snippet below to upload to the default SharePoint Library named "Documents":
String fileToUpload = "C:/Users/Administrator.CONTOSO2016/Desktop/Test.txt";
String sharePointSite = "http://sp2016/sites/dev/";
String libraryName = "Documents";
String fileName = fileToUpload.Substring(fileToUpload.LastIndexOf("\\") + 1);
using (ClientContext context = new ClientContext(sharePointSite))
{
FileCreationInformation FCInfo = new FileCreationInformation();
FCInfo.Url = "http://sp2016/sites/dev/Shared%20Documents/Test.txt";
FCInfo.Overwrite = true;
FCInfo.Content = System.IO.File.ReadAllBytes(fileToUpload);
Web web = context.Web;
List library = web.Lists.GetByTitle(libraryName);
Microsoft.SharePoint.Client.File uploadfile = library.RootFolder.Files.Add(FCInfo);
uploadfile.CheckIn("testcomment",CheckinType.MajorCheckIn);
context.ExecuteQuery();
}
Console.WriteLine("Success");