使用 URL 从 SharePoint 列表下载所有文档

Download all documents from SharePoint List using the URL

我想知道如何使用 SharePoint 客户端对象模型 (CSOM) (Microsoft.SharePoint.Client) 从 SharePoint 列表下载所有文档,并且列表完整 URL。

例如,如果 URL 是 http://teamhub.myorg.local/sites/teams/it/ISLibrary/Guides/

是否可以直接连接到 URL 并检索存储在那里的所有文档?

我已经尝试了下面的代码,但出现错误,而且似乎需要我将 URL 分成两部分。

            string baseURL = "http://teamhub.myorg.local/sites/";
            string listURL = "teams/it/ISLibrary/Guides/";

            var ctx = new ClientContext(baseURL);
            ctx.Credentials = new SharePointOnlineCredentials(userName, SecuredpassWord);
            var list = ctx.Web.GetList(listURL);
            ctx.Load(list);
            ctx.ExecuteQuery();
            Console.WriteLine(list.Title);

当我 运行 这段代码时,我只是得到一个 "File not found" 错误。

可以通过简单地在某处传递完整的 url 来完成吗?

我将需要进行此连接并为许多不同的列表获取所有文档 100 次以上,因此最好有一种方法可以使用完整的 URL.

如有任何建议,我们将不胜感激。谢谢

Microsoft.SharePoint.Client.Web.GetListByUrl 使用 webRelativeUrl,例如:

我的网站:https://tenant.sharepoint.com/sites/TST,图书馆:https://tenant.sharepoint.com/sites/TST/MyDoc4

因此代码为:

Web web = clientContext.Web;
var lib=web.GetListByUrl("/MyDoc4");

您分享的listURL好像是一个文件夹,所以我们可以得到文件夹和文件夹中的文件如下:

Web web = clientContext.Web;
                Folder folder = web.GetFolderByServerRelativeUrl("/sites/TST/MyDoc4/Folder");
                var files = folder.Files;                
                clientContext.Load(files);
                clientContext.ExecuteQuery();

下载文件:

foreach (var file in files)
                {
                    clientContext.Load(file);
                    Console.WriteLine(file.Name);
                    ClientResult<Stream> stream = file.OpenBinaryStream();
                    clientContext.ExecuteQuery();
                    var fileOut = Path.Combine(localPath, file.Name);

                    if (!System.IO.File.Exists(fileOut))
                    {
                        using (Stream fileStream = new FileStream(fileOut, FileMode.Create))
                        {
                            CopyStream(stream.Value, fileStream);
                        }
                    }
                }

private static void CopyStream(Stream src, Stream dest)
    {
        byte[] buf = new byte[8192];

        for (; ; )
        {
            int numRead = src.Read(buf, 0, buf.Length);
            if (numRead == 0)
                break;
            dest.Write(buf, 0, numRead);
        }
    }