从Sharepoint CSOM下载文件时访问被拒绝

时间:2018-10-10 15:43:17

标签: c# sharepoint csom

我正在尝试从客户端Sharepoint网站下载文件。我正在使用sharepoint CSOM。

我的代码如下:

using Microsoft.SharePoint.Client;

var username = "username";
var password = "pass";

var url = "https://myclient.sharepoint.com/";
var fileurl = "https://myclient.sharepoint.com/teams/folder1/folder%20x/somefile.docx";
using (ClientContext context = new ClientContext(url))
{    
    SecureString passWord = new SecureString();
    foreach (char c in password.ToCharArray()) passWord.AppendChar(c);
    context.Credentials = new SharePointOnlineCredentials(username, passWord);

    Uri filename = new Uri(fileurl);
    string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
    string serverrelative = filename.AbsolutePath;

    Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(serverrelative);
    context.Load(file);
    ClientResult<Stream> streamResult = file.OpenBinaryStream();
    context.ExecuteQuery();
    var file2 = streamResult.Value;
}

问题是我的访问被拒绝,但是当我使用相同的凭据登录时,我可以成功下载文件。

  • Sharepoint中是否有单独的权限可以从API而不是从UI下载文件?
  • 可能是文件夹名称中的空格吗?

更新

已确认这与文件夹或文件名中的空格无关。

2 个答案:

答案 0 :(得分:0)

如果SharePoint网站使用multiple authentication providers using a set of Windows credentials(也与SharePoint Online相关),则附加标头必须包含在请求中:X-FORMS_BASED_AUTH_ACCEPTED,其值为f

对于ClientContext class,标题可以这样包含:

ctx.ExecutingWebRequest += (sender, e) =>
{
    e.WebRequestExecutor.WebRequest.Headers["X-FORMS_BASED_AUTH_ACCEPTED"] = "f";
};

示例

var file = ctx.Web.GetFileByUrl(fileAbsUrl);
ctx.Load(file);
var streamResult = file.OpenBinaryStream();
ctx.ExecuteQuery();


//save into file
using (var fileStream = System.IO.File.Create(@"C:\path\filename.docx"))
{
   streamResult.Value.Seek(0, SeekOrigin.Begin);
   streamResult.Value.CopyTo(fileStream);
}
  

注意:使用GetFileByUrl method可以接受绝对网址

,而不是转换为相对网址

答案 1 :(得分:0)

问题是我没有连接到正确的URL(新的ClientContext(URL)

我正在连接到:https://myclient.sharepoint.com/

我应该已经连接到:https://myclient.sharepoint.com/teams/folder1/