使用 C# 将 excel 个文件从 Sharepoint 站点下载到本地系统

Download excel files from sharepoint site to local system using C#

我需要将 excel 文件从共享点下载到我的本地系统。 我写了下面的方法。

    internal static void DownloadFilesFromSharePoint(string siteUrl, string folderPath, string tempLocation)
    {
        ClientContext ctx = new ClientContext(siteUrl);
        ctx.Credentials = new NetworkCredential("username", "password");

        FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(folderPath).Files;

        ctx.Load(files);
        ctx.ExecuteQuery();----FAILED HERE

        foreach (File file in files)
        {
            FileInformation fileInfo = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
            ctx.ExecuteQuery();

            var filePath = tempLocation + file.Name;
            using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
            {
                fileInfo.Stream.CopyTo(fileStream);
            }
        }
    }

要调用上述方法,我在 Main 方法中有以下内容:

    public static void Main()
    {
    Program.DownloadFilesFromSharePoint("http://sp.frk.com/teams/ResearchSystemsSupport/GT%20Resources/Forms/AllItems.aspx", "/TeamDocuments", @"c:\");

    }

但是上面的代码不起作用。 我已经在调试时标记了代码给出异常的点(通过标记 ---- FAILED HERE)。任何人都可以指出这里的问题。 谁能帮我this.Please,如果可以的话也给我一个详细的解释。

替换下面的代码

Program.DownloadFilesFromSharePoint("http://sp.frk.com/teams/ResearchSystemsSupport/GT%20Resources/Forms/AllItems.aspx", "/TeamDocuments", @"c:\");

Program.DownloadFilesFromSharePoint("http://sp.frk.com/teams/ResearchSystemsSupport", "GT%20Resources/TeamDocuments", @"c:\");

站点Url和文件夹路径不正确。

我终于找到了下面粘贴的有效代码。 正如 LZ_MSFT 在评论中指出的那样,我重新检查了我正在传递的共享点 link,他们错了,所以改变了它,它起作用了。 同样在网络凭据中,添加了域。

    static void DownloadFilesFromSharePoint(string siteUrl, string siteFolderPath, string localTempLocation)
    {
        ClientContext ctx = new ClientContext(siteUrl);
        ctx.Credentials = new NetworkCredential("username", "password", "Domain");

        FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(siteFolderPath).Files;

        ctx.Load(files);
        if (ctx.HasPendingRequest)
        {
            ctx.ExecuteQuery();
        }

        foreach (File file in files)
        {                
                FileInformation fileInfo = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
                ctx.ExecuteQuery();

                var filePath = localTempLocation + "\" + file.Name;
                System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);

                fileInfo.Stream.CopyTo(fileStream);

        }
    } 

调用函数:

    static void Main(string[] args)
    {
        Program.DownloadFilesFromSharePoint(@"http://sp.frk.com/teams/ResearchSystemsSupport", @"http://sp.frk.com/teams/ResearchSystemsSupport/Global%20Equity%20Group/Daily_Checks", @"C:\Temp");       
    }