我需要从sharepoint下载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)。任何人都可以在这里指出问题。 有人可以帮我吗。如果可以的话,请给我详细的解释。
答案 0 :(得分:0)
替换下面的代码
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:\");
网站网址和文件夹路径不正确。
答案 1 :(得分:0)
我终于找到了下面粘贴的有效代码。 正如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");
}