使用 C# 将 Excel 文件从 SharePoint 站点下载到本地系统



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

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

但是上面的代码不起作用。 我已经标记了代码在调试时给出异常的点(通过在此处标记----失败(。谁能指出这里的问题。 谁能帮我这个。如果可以的话,也请给我一个详细的解释。

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

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

替换下面的代码

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 和文件夹路径不正确。

最新更新