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

问题描述 投票:0回答:1

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

例如,如果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);

当我运行此代码时,我只是得到一个“找不到文件”错误。

可以通过简单地传递到某个地方的完整URL来完成吗?

我将需要进行此连接,并为许多不同的列表提供100次的所有文档,因此最好是使用完整的URL来实现它。

任何建议表示赞赏。谢谢

c# .net sharepoint csom
1个回答
1
投票

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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.