使用 List.RootFolder.Files.Add 将文件上传到 SharePoint 时如何解决异常 (C#)

How to resolve exception when uploading file to SharePoint using List.RootFolder.Files.Add (C#)

上下文:我正在尝试将大量文件上传到 SharePoint 库。我会在这里调用库Library Name。 为简单起见,我将只尝试在下面的代码中上传一个文件。此文件的路径将为 C:/Users/UserName/Desktop/Test.txt 我将调用 SharePoint 网站 http://share-internal.CompanyName.com/Section/Subsection

这是我使用的代码:

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");
        }
    }
}

我在 context.ExecuteQuery(); 行遇到的问题。 当我尝试将一个文件添加到 SharePoint 库时,Library Name 我收到以下异常: Microsoft.SharePoint.Client.ServerException: 'Value does not fall within the expected range.'

我尝试过的事情:

这让我相信我的列表名称和站点 URL 是正确的,所以我对此时可能导致问题的原因感到困惑。

设置FCInfo.Url属性时请使用SharePoint库文件夹url,我修改下面的代码片段上传到名为"Documents"的默认SharePoint库:

            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");